【问题标题】:TypeScript relative path import not working in WebpackTypeScript 相对路径导入在 Webpack 中不起作用
【发布时间】:2018-01-06 11:08:25
【问题描述】:

我使用相对路径在 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

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

【问题讨论】:

  • 您的webpack.config.js 文件在哪里?
  • @Saravana 我已将信息添加到答案中的项目结构中。
  • 你能发布你的tsconfig.json吗?只要您的tsconfig.json 中没有任何路径映射,这应该可以工作。
  • @Saravana 添加 tsconfig。该项目使用 TypeScript 编译器 (tsc) 完美构建。
  • 您是否在 Widget.ts 中导出了 Widget 类?还有您要导入哪个文件?

标签: typescript webpack


【解决方案1】:

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 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多