Webpack 和 TypeScript:找不到模块:错误:无法解析“文件”或“目录”

Fra*_*rzi 0 typescript webpack

我正在尝试使用 Webpack 编译 TypeScript,但由于某些原因,它在导入时失败:

./path/to/MySource.ts 中的错误未找到模块:错误:无法解析“文件”或“目录”./path/to/MyIncludedFile in ...

尽管MyIncludedFile.ts实际上存在并且 IDE 也可以识别导入,但 TypeScript 编译器找不到该文件。

Fra*_*rzi 8

运行 Webpack--display-error-detail我得到了一些额外的信息:

/path/to/MyIncludedFile doesn't exist
/path/to/MyIncludedFile.webpack.js doesn't exist
/path/to/MyIncludedFile.web.js doesn't exist
/path/to/MyIncludedFile.js doesn't exist
/path/to/MyIncludedFile.json doesn't exist
Run Code Online (Sandbox Code Playgroud)

因此,我意识到 Webpack 并没有寻找正确的扩展名,在我的例子中是.ts.

为了解决这个问题,我修改了webpack.config.js添加以下内容:

resolve: {
    extensions: ['.ts']
}
Run Code Online (Sandbox Code Playgroud)

在我的模块配置中。更具体地说,我的模块 webpack conf 现在看起来像这样:

module.exports = [
  {
      entry: /* my entry config */
      output: {
          /* my output config */
      },
      module: {
          loaders: [
              {
                  test: /\.ts/,
                  loaders: ['ts-loader']
              }
          ]
      },
      /* ... other stuff ... */
      resolve: {
          extensions: ['.ts']
      }
  },
  /* ... other modules ... */
]
Run Code Online (Sandbox Code Playgroud)


Rob*_*rto 5

我也遇到了这个错误,并且也尝试过--display-error-details(在较新的 webpack 版本中,参数有一个尾随s!)。

结果我忘记了扩展数组中的点。添加它们解决了问题。

resolve: {
  extensions: ['.ts', '.tsx', '.js']
//              ^      ^       ^
//              |      |       |
//           don't forget these dots!
}
Run Code Online (Sandbox Code Playgroud)

我想,有时是微小的细节和巨大的错误日志导致了解决方案。希望它对将来的人有所帮助。