TypeScript 相对路径导入在 Webpack 中不起作用

标签 typescript webpack

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

相关文章:

javascript - 两个数组中的元素组合的逻辑(Javascript/Typescript)

javascript - 从对象数组中删除元素后,Angular 2 View 未更新

angular - 错误类型错误 : Cannot read properties of undefined (reading 'title' )

angular - 回调函数不会调用其类的其他成员函数

reactjs - 如何使用 Vite 根据环境提供不同的 index.html?

javascript - 失败 TFS 建立在像 TC 这样的指标变化上

asp.net - 任务运行程序资源管理器 ASP.NET - 在严格模式之外尚不支持 block 范围声明

css - extract-text-webpack-plugin 不提取 css

javascript - 在兄弟组件之间传递数据

reactjs - 从开发工具中的检查元素查找原始源文件路径