reactjs - 在导入的 react node_module 中出现 Typescript 编译错误,即使它在 tsconfig.json 中被排除了
我一直在尝试看看是否能让我的 TypeScript 构建忽略 node_modules(特别是 React),过程非常有趣。我的 tsconfig.json 告诉它要忽略该文件夹,但它仍然被编译,我不确定原因。我怀疑可能是因为它被包含文件中的某个文件导入了,也许是这样?
这是一个错误的例子,类似的还有很多:
ERROR in /Users/rw3iss/Sites/site/src/project/public/node_modules/@types/react/index.d.ts
(3606,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'feTile' must be of type 'SVGProps<SVGFETileElement>', but here has type 'SVGProps<SVGFETileElement>'.
我的 tsconfig.json 看起来是这样的:
{
"compilerOptions": {
"jsx": "react",
"target": "es6",
"module": "commonjs",
"noEmitOnError": true,
"noImplicitAny": false,
"experimentalDecorators": true,
"sourceMap": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true,
"allowJs": true,
"outDir": "build",
"noResolve": false,
"moduleResolution": "node",
"typeRoots": [
"./node_modules/@types",
"./secure/node_modules/@types",
"./public/node_modules/@types"
],
"types": [ "react" ]
},
"filesGlob": [
],
"include": [
"secure/src/**/*",
"public/react_src/**/*"
],
"exclude": [
"node_modules/**/*",
"public/node_modules/**/*",
"secure/node_modules/**/*",
"public/dist"
],
"types": [ "react" ]
}
我正在尝试使用 webpack/ts-loader 进行编译,我的 webpack 配置是:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: {
app: [
APP_DIR + '/react_src/Secure.tsx',
APP_DIR + '/react_src/DicomViewer.tsx'
]
},
output: {
publicPath: '/',
path: BUILD_DIR, // 'dist'
filename: '[name].js', // 'index.js'
//libraryTarget: 'umd'
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
modules: [ 'node_modules', 'src' ]
},
module: {
rules: [
{
test: /\.(t|j)sx?$/,
include: APP_DIR,
exclude: [
path.resolve(__dirname, 'node_modules'),
'../public/node_modules',
'../node_modules'
],
loader: ['ts-loader']
}
]
}
};
module.exports = config;
有人能告诉我为什么会发生这些错误吗?还有可能的话,怎么避免它们以及在导入的 node_modules 中可能出现的其他错误?
更新:我删除了 'typeRoots' 下的所有内容,并将 'types' 设置为空 []:
"typeRoots": [],
"types": []
但它仍然报同样的错误。我只是想弄清楚为什么……
答案#1
我无法让我的 TypeScript 构建忽略 node_modules(特别是 React)。我的 tsconfig.json 已经告诉它忽略该文件夹,但它仍然在被编译,我不确定原因是什么。
该错误与 @types 目录中的 React 类型声明有关。即使我们排除了 node_modules,@types 目录仍然会被包含在编译中。
这是来自文档的一些进一步的相关信息:
默认情况下,所有可见的“@types”包都会被包含在你的编译中……如果指定了 typesRoots,则只会包含 typeRoots 下的包……如果指定了 types,则只会包含列出的包。
你的 tsconfig 包含一个 types 属性,指定为 ["react"]。将 types 属性更改为空数组 [] 可能会解决该错误。请注意,types 属于 compilerOptions 下,而不是顶层。
另请参阅 https://github.com/Microsoft/TypeScript/issues/11257