tsc throws TS2307: Cannot find module for a local file
解决方案
{
"compilerOptions": {
//"allowImportingTsExtensions": true,
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
1. TS1208: 'xxx.ts' cannot be compiled under '--isolatedModules' 错误
错误原因
--isolatedModules 选项要求每个文件都必须是一个模块(即包含 import、export 语句或者空的 export {}),而当前这些文件被视为全局脚本文件,不满足该要求。
解决办法
在这些被视为全局脚本的文件(如 src/components/CreateGroupModal/api/index.ts、src/components/CreateGroupModal/api/type.ts、src/pages/container/ChatList/api/index.ts、src/pages/container/ChatList/api/type.ts)中添加 export {} 语句,将其转换为模块。例如:
收起
typescript
// src/components/CreateGroupModal/api/index.ts
export {};
// 其他代码...
2. TS2691: An import path cannot end with a '.tsx' extension 错误
错误原因
TypeScript 默认不允许在导入路径中使用 .tsx 扩展名,这是为了保证代码在不同环境(如编译后)的兼容性。
解决办法
去掉导入路径中的 .tsx 扩展名。将 src/main.tsx 中的导入语句修改为:
收起
typescript
import App from './App';
3. TS5023: Unknown compiler option 'allowImportingTsExtensions' 错误
错误原因
allowImportingTsExtensions 不是 TypeScript 编译器的标准选项,TypeScript 不识别该选项。
解决办法
从 tsconfig.json 中移除 allowImportingTsExtensions 选项。修改后的 tsconfig.json 示例如下:
收起
json
{
"compilerOptions": {
// 移除下面这行
// "allowImportingTsExtensions": true,
// 其他选项...
},
// 其他配置...
}
##打包成功