Vue CLI集成Electron使用原生模块时遭遇“Unexpected character (1:0)”错误,如何添加native-ext-loader解决?
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
mainProcessWebpackConfigensures we’re modifying the Webpack setup for Electron’s background process where you’re usingssh2. If you also use native modules in the renderer process, add an identical rule underrendererProcessWebpackConfig. - Path Rewriting: The
rewritePathoption fixes path mismatches between environments:- In development,
.nodefiles stay in their originalnode_modulessubdirectories. - In production, Electron Builder packages native modules into the
resourcesfolder of your built app.
- In development,
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

