目录
一、Window 上安装Node.js
1.nodejs官网下载最新版:https://nodejs.org/en/download/
一路安装下一步即可,安装目录:D:\Program Files\nodejs
2.配置环境变量:
在环境变量的Path中加入:D:\Program Files\nodejs
在cmd命令行查看版本:
证明nodejs已经安装成功!!
二、npm安装electron
由于各种资源的不稳定性,所以采取以下安装:
①先安装nrm:npm i -g nrm②安装源切换到taobao:nrm use taobao③最后安装electron:npm i electron-prebuilt
安装后路径:C:\Users\Admin.000\node_modules\electron-prebuilt
执行文件electron.exe在dist目录下
三、配置html工程
样例工程名:gmdssapk,工程结构如图:
从C:\Users\Admin.000\node_modules\electron-prebuilt路径下copy出cli.js和package.json放到项目工程路径下
追加main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// 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 win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'madss.html'), #因为我的入口html是mdss.html
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// 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.
win = 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', () => {
// 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', () => {
// 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 (win === null) {
createWindow()
}
})
根据实际情况更改package.json
比如把package.json中:改成main.js
四、开始打包
cmd打开命令窗口,进入到项目目录:
输入 npm install electron-packager -g全局安装我们的打包神器
在项目目录下执行以下命令:D:\HBuilderProject\gmdssapk
electron-packager . gmdss --win --out=release --arch=x64 --electron-version=1.4.13 --overwrite
打包成功!!!
在项目的/release文件夹下找到打包的文件目录:D:\HBuilderProject\gmdssapk\release\gmdss-win32-x64
运行里面的gmdss.exe,即出现客户端画面
以上是最简单的打包方式,至于怎么修改窗口大小、菜单栏怎么加、怎么调用系统API这些,就给你慢慢去研究Electron了。
五、其它方式
还有更简便的,下载了个免配置版本:Electron-packager-build-project-master
放到了D:\HBuilderProject
里面有已将内容为 hello,world 的 index.html 网页通过 Electron 框架打包为 windows 环境下的桌面应用。
现只需将你的网页前端项目复制到 /resources/app/project 目录下,双击 exe 文件即可以桌面应用的方式运行你的网页。