TypeScript与Webpack集成:导入扩展名冲突问题求解
解决TypeScript与Webpack导入扩展名的冲突问题
我完全理解你的困扰——这种TS语法检查和Webpack打包需求的矛盾在新手集成时特别常见,咱们一步步来搞定它:
核心原因拆解
- TypeScript抛出的
ts(2691)错误,是因为它默认遵循"编译后转.js"的逻辑,要求导入路径不带.ts扩展名; - Webpack找不到无扩展名的
./testFunction,则是因为你没配置它自动识别.ts文件的规则,它默认只会查找.js、.json这类后缀的文件。
解决方案:同步TS与Webpack的模块解析规则
1. 配置tsconfig.json,适配无扩展名导入
如果项目根目录还没有tsconfig.json,先创建一个,然后添加/调整以下配置:
{ "compilerOptions": { "module": "ESNext", // 或CommonJS,根据你的项目模块规范选择 "moduleResolution": "node", "target": "ES6", "strict": true, "esModuleInterop": true, "resolveJsonModule": true, "extensions": [".ts", ".tsx", ".js", ".jsx"] // 告诉TS需要解析的文件扩展名 }, "include": ["src/**/*"] }
2. 更新Webpack配置,让它自动识别TS文件
在你的webpack.config.js中添加resolve字段,指定Webpack需要自动尝试的文件后缀:
const path = require('path'); module.exports = { mode: "development", entry: './src/index.ts', devtool: 'inline-source-map', output: { path: path.resolve(__dirname, 'build'), filename: "bundle.js" }, resolve: { // 关键配置:让Webpack自动查找这些后缀的文件 extensions: ['.tsx', '.ts', '.js'] }, module: { rules: [ { test: /\.txt$/, use: 'raw-loader' }, { test: /\.tsx?$/, loader: "ts-loader" } ] } };
3. 调整导入代码为规范写法
现在你可以把导入语句改成TypeScript推荐的无扩展名形式,两种工具都能兼容:
import testFunction from "./testFunction"; console.log("imported function: "+testFunction());
额外说明:如果非要保留.ts扩展名怎么办?
这种写法不推荐(因为编译后的JS会保留.ts后缀,可能引发后续运行问题),但如果确实需要,可以在tsconfig.json中设置allowImportingTsExtensions: true,同时确保Webpack的resolve.extensions包含.ts,这样也能让两者兼容。
内容的提问来源于stack exchange,提问作者Supperhero
相关产品推荐
相关产品推荐

