vite+vue+electron快速搭建可打包框架
1 快速生成vite2+Vue3框架,作为后续基础
npm init @vitejs/app project-name
cd project-name
npm install
npm run dev
此处需运行并生成dist文件夹
2 为vue引入electron框架
根目录添加 .npmrc文件
内容:
electron_mirror=http://cdn.npm.taobao.org/dist/electron/
之后安装所需的启动及打包模块:
npm install electron --save-dev
npm install electron-builder --save-dev electron 打包
3 手动添加electron运行所需的配置文件(preload.js+main.js)
两个文件均添加至项目根目录
main.js内容:
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('dist/index.html')
// mainWindow.loadURL('http://localhost:3000/')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
preload.js内容:
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
4 为使Vite能够适应electron,更改vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// import { require } from 'yargs'
const path = require('path')
// https://vitejs.dev/config/
export default defineConfig({
base: path.resolve(__dirname, './dist'),
plugins: [vue()]
})
5 保证打包成功的配置详情(最简洁)
{
"name": "test",
"version": "0.0.0",
"main": "main.js",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"electron:start": "vite build & electron .",
"dist": "electron-builder"
},
"build":{
"appId": "cloudDoc",
"productName": "test1",
"directories": {
"output": "build"
},
"win": {
"target": [
{
"target": "nsis" ,
"arch": [
"ia32"
]
}
]
}
},
"dependencies": {
"vue": "^3.2.16"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.9.3",
"electron": "^15.3.0",
"electron-builder": "^22.13.1",
"vite": "^2.6.4"
}
}
后续补充
1.区分发布和开发环境(开发hotreload)
判断环境,正式打包:mainWindow.loadFile(‘index.html’)
开发调试:mainWindow.loadURL(http://localhost:3000/)
作者:邹小猪
链接:https://www.jianshu.com/p/1260904a62dd
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。