带电子的 Vue CLI - 使用本机模块时出现意外字符 (1:0)

Vue CLI with electron - Unexpected character (1:0) when using native modules

在一些流行的 NodeJS 库中,例如ssh2 或 node-pty,有本地编译代码作为库的一部分。 使用

创建项目
vue create my-project
vue add electron-builder
yarn add ssh2

然后在后台进程中导入和使用 ssh2 的 Client 导致以下错误 electron:build

ERROR  Failed to compile with 1 errors                                                                                                                                        5:29:10 PM

 error  in ./node_modules/cpu-features/build/Release/cpufeatures.node

Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

 @ ./node_modules/cpu-features/lib/index.js 1:16-60
 @ ./node_modules/ssh2/lib/protocol/constants.js
 @ ./node_modules/ssh2/lib/client.js
 @ ./node_modules/ssh2/lib/index.js
 ...

许多其他库或传递依赖项都会出现此错误,原因是 Webpack 链上缺少 native-ext-loader。我明白为什么默认不包含它,我想看看添加它的最佳方式是什么。

我找到的一个解决方案是:

  1. 添加yarn add -D native-ext-loader(我的版本是2.3.0,electron在13.x)
  2. 调整 vue.config.js 并像这样添加 chainWebpackMainProcess
const path = require('path')
module.exports = {
  pluginOptions: {
    electronBuilder: {
      builderOptions: {
        // options placed here will be merged with default
        mac: {
          target: 'dmg',
          icon: 'build/icon.icns',
          asar: true
        }
      },
      preload: 'src/preload.ts',
      chainWebpackMainProcess(config) {
        config.module
          .rule("node")
          .test(/\.node$/)
          .use("native-ext-loader")
          .loader("native-ext-loader")
          .options(
            process.env.NODE_ENV === "development"
              ? {
                rewritePath: path.resolve(__dirname, "native"),
              }
              : {}
          )
      }
    }
  }
}

electron:buildelectron:serve 现在都在工作,ssh2 客户端很高兴地通过 ipcMain 将标准输出传送到渲染器。不过不确定这是最优雅的解决方法。