You need to enable JavaScript to run this app. 使用webpack构建服务端渲染React应用时报Unexpected token 'export'错误
优惠活动
大模型
产品
解决方案
定价
更多

使用webpack构建服务端渲染React应用时报Unexpected token 'export'错误

Node 环境渲染 React 项目 Webpack 打包报错问题

相关配置信息

Webpack 内的 Babel 配置

module.exports = {
  // 配置webpack对所有匹配文件执行Babel转译
  module: {
    rules: [
      {
        test: /\.(js|ts|tsx)?$/,
        loader: 'babel-loader',
        include: [
          path.join(__dirname, 'src'),
          path.join(
            __dirname,
            '..',
            'node_modules/@platformbuilders/react-ui/dist/index',
          ),
        ],
        options: {
          babelrc: false,
          presets: [
            '@babel/react',
            '@babel/preset-typescript',
            [
              '@babel/preset-env',
              {
                loose: true,
                modules: false,
              },
            ],
          ],
          plugins: [
            '@babel/proposal-object-rest-spread',
            ['@babel/plugin-proposal-decorators', { legacy: true }],
            ['@babel/plugin-proposal-class-properties', { loose: true }],
            'dynamic-import-node',
            '@babel/plugin-syntax-dynamic-import',
            '@babel/plugin-transform-runtime',
          ],
        },
      },
      {
        test: /\.html$/,
        use: 'html-loader',
      },
    ],
  },
};

执行命令

  • 打包命令:webpack --config webpack.server.cjs --mode development
  • 启动命令:nodemon --watch build --exec node ./build/dist/assets/app.js

运行错误日志

/mnt/f/Apps/Github/services-portal-landing/node_modules/@platformbuilders/react-ui/dist/index.js:1
export * from './components';
^^^^^^

SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:1116:16)
at Module._compile (internal/modules/cjs/loader.js:1164:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Module.require (internal/modules/cjs/loader.js:1089:19)
at require (internal/modules/cjs/helpers.js:73:18)
at Object.@platformbuilders/react-ui (/mnt/f/Apps/Github/services-portal-landing/build/dist/assets/app.js:9240:18)
at __webpack_require__ (/mnt/f/Apps/Github/services-portal-landing/build/dist/assets/app.js:9660:41)
at Object../src/components/index.ts (/mnt/f/Apps/Github/services-portal-landing/build/dist/assets/app.js:5927:84)

问题定位指向@platformbuilders/react-ui模块,已尝试多种修复方案未生效。

补充:@platformbuilders/react-ui dist目录下的tsconfig配置

{
  "compilerOptions": {
    /* 基础配置 */
    "target": "es6",
    "module": "es6",
    "lib": ["es6", "DOM"],
    "types": ["react"],
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "dist",
    "importHelpers": true,
    "resolveJsonModule": true,
    "jsx": "react",
    "baseUrl": ".",
    "skipLibCheck": true,
    /* 严格检查配置 */
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "suppressImplicitAnyIndexErrors": true,
    /* 附加检查配置 */
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    /* 模块解析配置 */
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "compileOnSave": true,
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

根因分析

报错的核心逻辑是:

  1. Node.js 原生运行环境采用 CommonJS 模块规范,无法直接识别 ES Module 标准的export、import语法
  2. 第三方包@platformbuilders/react-ui的tsconfig配置指定了"module": "es6",打包输出的dist文件全部为ESM格式语法,没有提供Node可直接识别的CommonJS入口
  3. 现有Webpack Babel配置存在两处关键问题:
    • include规则仅指向了@platformbuilders/react-ui/dist/index单个文件,没有覆盖该包下所有关联的JS模块,导致大部分带ESM语法的文件没有被Babel转译
    • @babel/preset-env设置了modules: false,意味着Babel不会主动将ESM语法转译为CommonJS格式,最终打包产物中保留了原生的export语句,被Node加载时直接触发语法错误。

修复步骤

  • 修正Babel的include匹配范围,覆盖整个@platformbuilders/react-ui包目录,不要仅匹配单个文件:
    include: [
      path.join(__dirname, 'src'),
      // 替换原有单文件匹配为整包目录匹配
      path.join(__dirname, 'node_modules/@platformbuilders/react-ui'),
    ]
    
  • 调整服务端打包场景下的@babel/preset-env配置,关闭modules: false,显式指定转译模块格式为CommonJS,同时配置Node运行目标,减少多余转译:
    [
      '@babel/preset-env',
      {
        loose: true,
        // 替换原有modules: false为commonjs格式转译
        modules: 'commonjs',
        targets: {
          node: 'current'
        }
      },
    ],
    
  • 移除不适用的dynamic-import-node插件(该插件为Jest测试场景设计,在Webpack服务端打包场景下会和现有配置产生冲突),保留@babel/plugin-syntax-dynamic-import即可满足动态导入语法的解析需求。
  • 重新执行打包命令,检查输出的服务端代码中是否还存在原生export语法,确认无问题后再启动nodemon服务。

内容的提问来源于stack exchange,提问作者Alan Jones Rios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 02:54:02