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

CommonJS遗留项目引入ES模块后webpack打包报错:center_ is not a function

问题分析与修复方案

问题本质

基于CommonJS的遗留项目引入.mjs文件后,webpack打包运行时出现center_ is not a function错误。根源是@turf/center作为ES模块,其默认导出被webpack处理为包含default属性的对象,但打包代码直接调用该对象而非内部的函数。

原因说明

  • 开发环境下@babel/register自动完成了ES模块与CommonJS的互操作,隐式提取了default属性;
  • 生产环境webpack配置中,nodeExternals默认将node_modules模块视为CommonJS引入,而@turf/center实际是ES模块,导致导出结构不匹配。

修复方案

方案1:配置Babel自动处理模块互转

安装@babel/plugin-transform-modules-commonjs插件,让Babel在转译时自动处理ES模块默认导出的转换:

npm install @babel/plugin-transform-modules-commonjs --save-dev

修改webpack的babel-loader配置:

module: {
    rules: [
        {
            test: /\.(mjs|js)$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: [
                        ['@babel/plugin-transform-modules-commonjs', {
                            interopRequireDefault: true // 自动处理默认导出的互操作
                        }]
                    ]
                }
            }
        }
    ]
}

方案2:调整nodeExternals适配ES模块

修改nodeExternals配置,让它以ES模块方式引入外部依赖:

externals: [nodeExternals({
    importType: 'module',
    modulesDir: path.resolve(__dirname, 'node_modules')
})],

同时在webpack配置中启用ES模块输出支持(webpack 5+):

module.exports = {
    // ...其他配置
    experiments: {
        outputModule: true
    }
}

方案3:临时手动修正导入(应急用)

若暂时无法修改配置,可直接在代码中手动提取default函数:

import centerModule from '@turf/center';
const center = centerModule.default;

let testVar = center(boundingBoxPolygon);

总结

这是ES模块与CommonJS互操作的配置问题,并非工具bug。优先通过方案1或2从配置层面解决,避免后续其他ES模块依赖出现同类问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:54:53