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

Posted

技术标签:

【中文标题】带有电子的 Vue CLI - 使用本机模块时出现意外字符 (1:0)【英文标题】:Vue CLI with electron - Unexpected character (1:0) when using native modules 【发布时间】:2021-12-14 21:33:37 【问题描述】:

在一些流行的 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) 调整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 将标准输出传递给渲染器。不过,不确定这是最优雅的解决方法。

【讨论】:

以上是关于带有电子的 Vue CLI - 使用本机模块时出现意外字符 (1:0)的主要内容,如果未能解决你的问题,请参考以下文章