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

Node.js Webpack+Babel编译服务端代码遇Async函数解析错误求助

解决方案:修复Webpack编译Async函数的Module Parse错误

绝对需要调整Webpack配置——这个错误的核心就是你的async函数用到了ES2017的语法,但当前的Babel预设(es2015-node4和es2015)根本不支持解析这类语法,导致Webpack找不到合适的loader处理文件,才会抛出Unexpected token错误。

下面是具体的修复步骤:

1. 升级Babel依赖(推荐方案)

旧的es2015系列预设已经被废弃,建议换成更灵活的@babel/preset-env,它能根据你指定的目标Node版本自动转译所需的语法。同时需要安装插件处理async/await:

打开终端执行安装命令:

npm install --save-dev @babel/core @babel/preset-env babel-loader @babel/plugin-transform-runtime
npm install @babel/runtime

2. 修改Webpack配置文件

替换原来的Babel配置部分,让它使用新的预设和插件:

const webpack = require('webpack');
module.exports = {
  target: 'node',
  entry: ['./server/index.js', './node...'], // 保留你原来的entry内容
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                targets: {
                  node: 'current' // 自动适配你当前使用的Node版本,也可以指定具体版本比如'16'
                }
              }]
            ],
            plugins: ['@babel/plugin-transform-runtime']
          }
        }
      }
    ]
  },
  // 保留你原来的其他配置(output、plugins等)
};

3. 备选方案(如果不想升级Babel)

如果坚持使用旧的es2015预设,需要单独安装处理async的插件:

npm install --save-dev babel-plugin-transform-async-to-generator

然后在Babel options里添加这个插件:

options: {
  presets: ["es2015-node4","es2015"],
  plugins: ["transform-async-to-generator"]
}

不过还是更推荐升级到@babel/preset-env,它的维护性和适配性更好。

额外注意事项

  • 确保babel-loader和@babel/core的版本匹配(比如babel-loader 8.x必须搭配@babel/core 7.x),如果版本不兼容也会出现奇怪的错误。
  • 如果你有单独的.babelrc或babel.config.json文件,也需要同步更新里面的预设和插件配置,效果和Webpack里的options是一致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:30:56