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

Vue CLI集成Electron使用原生模块时遭遇“Unexpected character (1:0)”错误,如何添加native-ext-loader解决?

Fixing Webpack Error with Native Node Modules in Vue + Electron Builder Projects

When working with native Node.js modules like ssh2 (which depends on cpu-features with .node binary files) in a Vue + Electron Builder project, you’ll hit the "Module parse failed: Unexpected character" error because Webpack doesn’t handle binary .node files out of the box. Here’s the optimal solution to add native-ext-loader and resolve this issue:

Step 1: Install the Required Loader

First, install native-ext-loader as a dev dependency. Use whichever command matches your package manager:

# Using npm
npm install native-ext-loader --save-dev

# Using yarn
yarn add native-ext-loader --dev

Step 2: Configure Webpack in vue.config.js

Since you’re using vue-cli-plugin-electron-builder, you need to tweak the Webpack setup specifically for Electron’s main process (where you’re importing the ssh2 Client). Create or update your vue.config.js file with this code:

module.exports = {
  pluginOptions: {
    electronBuilder: {
      // Configure Webpack rules for the main/background process
      mainProcessWebpackConfig: {
        module: {
          rules: [
            {
              test: /\.node$/,
              loader: 'native-ext-loader',
              options: {
                // Adjust path based on environment to fix resolution issues
                rewritePath: process.env.NODE_ENV === 'development'
                  ? './node_modules/cpu-features/build/Release/'
                  : './resources/'
              }
            }
          ]
        }
      }
    }
  }
};

Key Notes on This Configuration:

  • Main Process Targeting: The mainProcessWebpackConfig ensures we’re modifying the Webpack setup for Electron’s background process where you’re using ssh2. If you also use native modules in the renderer process, add an identical rule under rendererProcessWebpackConfig.
  • Path Rewriting: The rewritePath option fixes path mismatches between environments:
    • In development, .node files stay in their original node_modules subdirectories.
    • In production, Electron Builder packages native modules into the resources folder of your built app.

Step 3: Test the Build

Run your Electron build command again:

npm run electron:build
# or
yarn electron:build

This should resolve the Webpack parsing error, as native-ext-loader now properly handles the binary .node files.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:32:45