首页 文章

TypeScript相对路径导入无法在Webpack中工作

提问于
浏览
0

我使用相对路径在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作为条目文件 .

我在这做错了什么?


Additional information:

项目文件夹结构:

c:\project
├─ src
│  ├─ index.ts
│  └─ components
│     └─ Widget.ts
├─ webpack.config.js
└─ tsconfig.json

Webpack配置:

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

1 回答

  • 2

    resolve.extensions 添加到webpack.config.js .

    {
        resolve: {
            extensions: ['.ts', '.js', '.json']
        }
    }
    

    当您在其中一个模块(ref)中编写无扩展导入时,webpack中的模块分辨率默认仅搜索 .js.json 文件 .

    所以当你写:

    import {Widget} from './components/Widget';
    

    Webpack默认只搜索这些文件:

    ./components/Widget.js
    ./components/Widget.json
    

    因此最终给出 Module not found 错误 .

相关问题