You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack+TS+ESM构建Express服务时配置文件加载报错求助

解决Webpack加载TS配置文件的扩展名错误问题

核心原因

在ESM模式下(package.json已设置"type": "module"),Node.js默认无法直接解析.ts文件,webpack-cli加载配置时会触发文件扩展名未知的错误。

解决方案步骤

1. 安装必要依赖

安装ts-node让Node能编译TS配置文件,同时安装@types/node提供类型支持:

npm install -D ts-node @types/node

2. 创建专属的TS配置文件

在项目根目录新建tsconfig.node.json,专门用于编译webpack配置文件,避免和项目源码的TS规则冲突:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "strict": true,
    "skipLibCheck": true,
    "resolveJsonModule": true
  },
  "include": ["config/webpack.config.ts"]
}

3. 修改构建命令

通过环境变量指定ts-node使用专属配置,同时让webpack-cli借助ts-node加载TS格式的配置文件:
修改package.json中的scripts字段:

{
  "scripts": {
    "build": "TS_NODE_PROJECT=./tsconfig.node.json ts-node --esm node_modules/webpack-cli/bin/cli.js --config config/webpack.config.ts --mode development"
  }
}

也可以直接执行以下命令测试:

TS_NODE_PROJECT=./tsconfig.node.json ts-node --esm node_modules/webpack-cli/bin/cli.js --config config/webpack.config.ts --mode development

4. 确保webpack配置文件的ESM语法正确

检查config/webpack.config.ts是否采用标准ESM写法,示例如下:

import path from 'path';
import type { Configuration } from 'webpack';

const config: Configuration = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js']
  },
  target: 'node'
};

export default config;

5. 隔离主项目TS配置(可选)

如果主项目的tsconfig.json的include字段包含了配置文件目录,建议调整为只包含源码目录,避免编译规则混淆:

{
  "include": ["src/**/*"]
}

关键注意点

  • Node.js 16的ESM支持需要给ts-node明确加上--esm参数,否则会默认以CommonJS模式处理,和项目的ESM模式冲突。
  • 单独的tsconfig.node.json可以让配置文件的编译规则独立于项目源码,避免互相干扰。

内容的提问来源于stack exchange,提问作者qwerty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:35:26