【问题标题】:An import path cannot end with a '.tsx' extension导入路径不能以“.tsx”扩展名结尾
【发布时间】:2021-08-27 18:23:45
【问题描述】:

我是 Typescript 的新手,正在尝试为 typescript 构建一个反应样板。但无法导入“.tsx”形式的组件。

我的 tsconfig 文件如下所示:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

我的 eslintrc 看起来像这样:

{
    "root": true,
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
        "react/jsx-filename-extension": [2, { "extensions": [".js", ".jsx", ".ts", ".tsx"] }],
        "linebreak-style": 0,
        "global-require": 0,
        "eslint linebreak-style": [0, "error", "windows"],
        "no-use-before-define": "off",
        "indent": [2, 2]
    }
}

【问题讨论】:

  • 您能否详细说明“无法导入 .tsx 格式的组件”的含义?你看到什么错误?附带说明一下,您可以尝试 Create React App 提供的 React + Typescript boilerplate,这是一个不错的起点。
  • 你能澄清一下吗? .tsx 不是一种公认​​的浏览器语言,因此您可能正在使用像 babel 和/或 webpack 这样的编译器。这很可能是您的 .tsx 文件阻塞的原因。

标签: reactjs typescript eslint tsx


【解决方案1】:

您可以编辑 tsconfig.json 文件并添加路径选项,如下所示:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": false,
    "paths": {
      "@/*": ["src/*"]
    },
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2021-09-20
    • 2021-03-14
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多