我使用相对路径在 TypeScript 中导入了一个模块。
// index.ts
import {Widget} from './components/Widget';
Webpack 给我以下错误:
ERROR in ./src/index.ts
Module not found: Error: Can't resolve './components/Widget' in
C:\project\src' @ ./src/index.ts 4:19-51
我的 webpack 配置文件非常基本,规则中有 ts-loader 并指向 index.ts 作为入口文件。
我在这里做错了什么?
附加信息:
项目文件夹结构:
c:\project
├─ src
│ ├─ index.ts
│ └─ components
│ └─ Widget.ts
├─ webpack.config.js
└─ tsconfig.json
网络包配置:
const path = require('path');
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{ test: /\.tsx?$/, use: 'ts-loader' }
]
}
};
module.exports = config;
tsconfig.json
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es6"
},
"include": [ "src/**/*" ],
"exclude": [
"node_modules"
]
}
版本:
webpack 3.1.0
typescript 2.4.1
ts-loader 2.2.2
最佳答案
将 resolve.extensions
添加到您的 webpack.config.js。
{
resolve: {
extensions: ['.ts', '.js', '.json']
}
}
当您在其中一个模块中编写无扩展导入时,webpack 中的模块解析默认仅搜索 .js
和 .json
文件 (ref) .
所以当你写的时候:
import {Widget} from './components/Widget';
Webpack 默认只搜索这些文件:
./components/Widget.js
./components/Widget.json
因此最终会出现Module not found
错误。
关于TypeScript 相对路径导入在 Webpack 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45406372/