一:引入electron
cnpm install electron --save-dev 在开发环境使用electron
二:build文件夹下增加electron-preload.js文件,内容可以为空。
主要用来在创建桌面窗口前定义一些window全局变量。可根据项目自行定义。如:window.isElectron = true 在项目中进行判断是否为桌面程序打开,可以调用electron的一些api
三:build文件夹下增加electron_dev.js文件
内容为:
// Modules to control application life and create native browser window
const {
app,
BrowserWindow,
Menu
} = require('electron') // 引入electron
const path = require('path') // 引入文件路径处理插件
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow // 定义桌面应用窗口
// 创建桌面应用窗口
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1280, // 初始宽度
height: 800, // 初始高度
minWidth: 1280, // 最小宽度
minHeight: 800, // 最小高度
webPreferences: {
nodeIntegration: true, // 可以使用nodejs原生api
preload: path.join(__dirname, 'electron-preload.js') // 创建桌面前引用的js文件,可以用来定义一些window全局变量
}
})
// and load the index.html of the app.
// mainWindow.loadFile('index.html')
mainWindow.loadFile(path.join(__dirname, '../dist/index.html')) // 桌面应用打开的html文件
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
// 定义窗口关闭后回调方法,关闭主进程
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// 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.on('ready', createWindow)
// Quit when all windows are closed.
// 所有的窗口页面关闭后,退出应用
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') app.quit()
})
// 创建窗口
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 (mainWindow === null) createWindow()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
四:修改config/index.js文件 build对象参数assetsPublicPath的值为‘./’,改成相对路径,否则打包后桌面程序请求不到资源
五:package.json文件中增加运行脚本
"electron_dev":"electron ./build/electron_dev.js"
然后执行npm run electron_dev
显示如下:
下一章讲解使用electron-packager打包