Vue3 Electron 框架快速搭建
一、安装vue/cli
https://cli.vuejs.org/zh/guide/installation.html
npm install -g @vue/cli
# OR
yarn global add @vue/cli
二、创建 Vue3 工程
有两种方式一种通过 vue ui 的方式去创建,我这里使用命令创建
vue create you_project_name
这里会让你选择版本,你可以使用vue2 或 vue3 都可以
三、添加插件
vue add electron-builder
四、启动
npm run electron:serve
五、可能遇到的 Bug 问题
1. 找不到 Module not found: Error: Can’t resolve ‘fs’
error in ./node_modules/electron/index.js
Module not found: Error: Can't resolve 'fs' in 'D:\Project\myProject\Vue\south_rain\node_modules\electron'
error in ./node_modules/electron/index.js
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
我遇到这个问题我头都要打死了,这个问题 100%
能解决;
为什么?
electron-builder 官方原话
从 VCPEB 的 v2.0 开始,Electron 默认处于禁用状态。这将阻止所有节点 API,例如 .这减少了nodeIntegrationrequire安全风险 (打开新窗口),并且是 Electron 团队推荐的最佳实践。
解决方案
- 修改
vue.config.js
文件 许多博文都没有说过这个,但是在生成的 background.js 中就有过提示//vue.config.js 文件,如果没有就创建一个 const {defineConfig} = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, pluginOptions: { electronBuilder: { nodeIntegration: true } }
- 修改创建窗口中的
const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { //是否开启node支持 nodeIntegration: true, //是否开启上下文隔离 contextIsolation: false } })