首页 > 解决方案 > Webpack: `export module` 导致模块解析失败: Unexpected token

问题描述

我目前正在尝试学习如何使用 TypeScript 编写 Webpack 代码。

我的包似乎工作,tsc运行没有错误并npx ts-node src/index.ts打印我的示例值。

索引.ts

import {Units} from './Units'

console.log(Units.Example.KM)

单位.ts

export module Units {
    export const Example = {
        KM: 1000,
    }  
}

但是,如果我尝试 npx webpack 唯一真正的代码行已经导致问题:

ERROR in ./src/Units.ts 1:7
Module parse failed: Unexpected token (1:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export module Units {
|     export const Example = {
|         KM: 1000,
 @ ./src/index.ts 1:0-32

webpack 5.47.1 compiled with 1 error and 1 warning in 184 ms

我的最小实现包括以下内容:

webpack.config.js

const path = require("path");

module.exports = {
  entry: {
    app: './src/index.ts'
  },
  
  resolve: {
    extensions: ['.js', '.ts']
  },
  
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },

  module: {
    rules: [{
      test: /\.js$/, // include .js files
      enforce: "pre", // preload the jshint loader
      use: [{
        //loader: "jshint-loader",
        loader: "babel-loader",
      }]
    }]
  },
};

tsconfig.json

{
  "compilerOptions": {
    "outDir": "lib",
    "strict": false,
  },
  "include": ["src/**/*.ts"]
}

我似乎找不到其他有这个问题的人,但我不明白这可能有什么问题,因为 TypeScript 运行时似乎没有问题。我错过了什么?

标签: javascripttypescriptwebpack

解决方案


推荐阅读