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

Webpack打包Node.js ESM代码仍生成require,如何改为使用import?

问题

我有一个采用ESM模块编写的Node.js应用,代码全程使用import和export语法。我希望通过Webpack对代码进行压缩打包,且不包含依赖(将node_modules文件夹放在打包产物旁)。但目前的问题是,即便在Webpack配置文件中设置了module相关选项,打包产物仍使用require而非import来引入库。由于我使用的部分库(如D3.js)不兼容require,因此必须使用import。

以下是我编写的Webpack配置:

import CopyWebpackPlugin from 'copy-webpack-plugin'
import nodeExternals from 'webpack-node-externals'

export default {
    devServer: {
        server: 'https',
    },
    entry: './server.js',
    experiments: {
        outputModule: true,
    },
    output: {
        filename: 'main.js',
        path: '/Users/test/Documents/test/back/dist',
        module: true,
        chunkFormat: 'module',
        chunkLoading: 'import'
    },
    target: 'node',
    mode: 'production',
    externals: [nodeExternals()],
    plugins: [
        new CopyWebpackPlugin({
            patterns: [
                { from: './views', to: 'views' }
            ]
        })
    ],
}

请问我哪里配置出错了?恳请各位提供帮助!


解决方案

问题出在webpack-node-externals的默认行为上——它默认会为外部依赖生成CommonJS风格的require语句,哪怕你已经配置了Webpack输出ESM模块。

你需要修改nodeExternals()的调用,传入importType: 'module'选项,让它生成ESM的import引用:

externals: [nodeExternals({
  importType: 'module'
})],

同时要确保项目根目录的package.json中设置了"type": "module",这样Node.js才会将打包后的main.js识别为ESM模块,避免运行时语法错误。

修改后的完整Webpack配置如下:

import CopyWebpackPlugin from 'copy-webpack-plugin'
import nodeExternals from 'webpack-node-externals'

export default {
    devServer: {
        server: 'https',
    },
    entry: './server.js',
    experiments: {
        outputModule: true,
    },
    output: {
        filename: 'main.js',
        path: '/Users/test/Documents/test/back/dist',
        module: true,
        chunkFormat: 'module',
        chunkLoading: 'import'
    },
    target: 'node',
    mode: 'production',
    externals: [nodeExternals({
      importType: 'module'
    })],
    plugins: [
        new CopyWebpackPlugin({
            patterns: [
                { from: './views', to: 'views' }
            ]
        })
    ],
}

这样打包后的产物就会用import引入外部依赖,适配D3.js这类仅支持ESM的库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:55:07