【问题标题】:Ignore *.js and *.jsx files with tsconfig.json使用 tsconfig.json 忽略 *.js 和 *.jsx 文件
【发布时间】:2019-03-27 01:51:53
【问题描述】:

这是我们尝试过的:

{
  "compilerOptions": {
    "target": "esnext",
    "moduleResolution": "node",
    "allowJs": true,
    "jsx": "react"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "src/**/*.js",
    "src/**/*.jsx",
  ]
}

当我们从命令行运行tsc 时,编译器会在jsxjs 文件中发现错误。例如,我们看到了这些错误。

src/components/foo/barHeaderStateOverview.jsx:90:46 
    - error TS8010: 'types' can only be used in a .ts file.

90   generateArbitraryData = (id: string, data: {path: string, title: string}) => {
                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/components/foo/barHeaderStateOverview.jsx:101:65 
    - error TS1005: ',' expected.

101     const arbitrary = this.generateArbitraryData('weight', data : (string | number));

问题可能是由this compiler behavior引起的:

...如果一个文件 B.ts 被另一个文件 A.ts 引用,则不能排除 B.ts,除非在“排除”列表中也指定了引用文件 A.ts。

我们的一些 *.ts 文件确实会导入 *.js 和 *.jsx 文件。有没有办法告诉编译器不要对 *.ts 文件导入的那些 *.js 和 *.jsx 文件进行类型检查?

【问题讨论】:

  • 你为什么在 javascript 文件中使用 typescript?您将在浏览器中出现错误,因为它无法解析 TS 或通过 typescript 编译器。还有允许 js 选项“允许编译 JavaScript 文件”。所以你可能希望那是假的。
  • @kyle 我们正在从 Flow 过渡到 TypeScript。 Flow 语法类似于 TypeScript 语法,tsc 无法弄清楚,“嘿,这些*.js 文件使用的是 Flow 语法而不是 TypeScript 语法。”
  • 您需要提供一些可以替换的存根,或者一起删除导入。通过导入模块,您要求编译器解析和使用该模块。你不能同时拥有它。
  • 设置allowJS: false

标签: reactjs typescript tsc


【解决方案1】:

对我们来说,这个 tsconfig 文件可以忽略所有 js 和 jsx 文件。

{
  "compilerOptions": {
    "outDir": "build",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom", "es2016", "es2017"],
    "sourceMap": true,
    "checkJs": false,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "experimentalDecorators": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "baseUrl": "./",
    "paths": {
      "~/*": ["*"]
    }
  },
  "include": ["./src/**/*.ts", "./src/**/*.tsx"],
  "exclude": ["node_modules", "build", "dist", "src/**/*.js", "src/**/*.jsx"]
}

此外,如果我们在 .jsx|.js 文件中导入 .tsx|.ts 文件,我们必须是显式的。

import someFile from "./path/to/file.tsx"

我们尚未测试,但如果修改为您的可能会运行:

    {
      "compilerOptions": {
        "target": "esnext",
        "moduleResolution": "node",
        "allowJs": true,
        "checkJs": false,
        "jsx": "react"
      },
      "include": [
        "./src/**/*.ts", "./src/**/*.tsx"
      ],
      "exclude": [
        "src/**/*.js",
        "src/**/*.jsx",
      ]
    }

我希望这会有所帮助。我们遇到了同样的问题,我们花了一段时间才把它弄好

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 2017-04-18
    • 2017-02-13
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2021-04-18
    相关资源
    最近更新 更多