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

旧版Electron(v6)下用Babel+Webpack编译Serialport(v11)报错排查

解决Electron v6 + Serialport v11的语法转译问题

问题根源

Electron v6内置的Chrome引擎版本为76,不支持ES2020的可选链(?.)和空值合并运算符(??),而Serialport v11的代码中使用了这些新语法。你的Babel配置未正确启用这些语法的转译规则,导致编译报错。

解决方案步骤

1. 安装必要的Babel插件

直接安装针对新语法的转译插件:

npm install @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing-operator --save-dev

2. 修正Babel配置文件(babel.config.js)

更新配置,明确指定Electron版本、升级corejs并添加新语法插件:

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: { electron: '6.0.0' }, // 直接指定Electron版本,避免读取package.json的潜在问题
        useBuiltIns: 'usage',
        corejs: 3, // 升级到corejs 3,对新语法/API的支持更完善
        modules: false // 交由Webpack处理模块打包,避免重复转译
      }
    ]
  ],
  plugins: [
    '@babel/plugin-proposal-optional-chaining',
    '@babel/plugin-proposal-nullish-coalescing-operator'
  ]
};

3. 修正Webpack配置文件(webpack.config.js)

移除babel-loader中的presets配置(避免覆盖根Babel配置),并确保Serialport相关的所有包都被转译:

module.exports = {
  // ...其他配置
  module: {
    target: 'electron-renderer',
    rules: [{
      test: /\.js$/,
      exclude: /node_modules\/(?!(@serialport|serialport))/, // 同时包含serialport和@serialport包
      use: {
        loader: 'babel-loader'
        // 移除options中的presets,使用项目根目录的babel.config.js
      }
    }]
  }
};

4. 额外注意事项

  • Electron v6自带的Node.js版本为v12.4.0,本地开发用Node.js v16不影响编译,但转译规则必须以Electron的运行环境为准。
  • 如果是主进程代码,需将Webpack的target改为electron-main。
  • 编译前可删除node_modules和dist目录,重新执行npm install和编译命令,避免缓存问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:12:34