你以为前端这辈子就只能写网页,搞浏览器吗?
在前端的世界里有这么一个神奇的框架——Electron。这个框架成功的为前端工程师开发桌面跨平台软件提供了可能!不仅如此,使用Electron开发的软件还具有开发速度快、开发周期短、维护成本低和跨平台等优秀特点!像 atom 甚至微软家的 vscode 无不是依赖 Electron 开发的优秀软件!
那么问题来了,如何使用 Electron 开发一个自己的软件呢?
说明
Electron Application 本质上还是一个 Node.js 程序。与 Node.js 模块相同,应用的入口是 package.json 文件。 一个最基本的 Electron 应用一般来说会有如下的目录结构:
your-app/
├── package.json
├── main.js
└── index.html
起点
首先,你需要新建一个文件夹,然后为自己的 App 取一个响亮的名字;
打开你的命令行工具,然后从该文件夹运行 npm init ,生成一个 package.json 文件(后面可以自己自己修改);
npm init
这是一个简易的 package.json 文件模板:
{
"name": "your-app",
"version": "0.1.0",
"main": "main.js", //如果 main 字段没有在 package.json 中出现,那么 Electron 将会尝试加载 index.js 文件(就像 Node.js 自身那样)。
"scripts": {
"start": "electron ." //你需要添加一个 start 脚本来指引 node 去执行当前的 package
}
}
安装 Electron
打开你的命令行工具,然后从该文件夹运行 npm install --save-dev electron(你也可以全局安装 npm install electron -g );
正式开始
1.编写 main.js 文件;
例:
const { app, BrowserWindow } = require('electron')
function createWindow () {
// 创建浏览器窗口
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// 并且为你的应用加载index.html
win.loadFile('index.html')
// 打开开发者工具
win.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
// 否则绝大部分应用及其菜单栏会保持激活。
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// 在macOS上,当单击dock图标并且没有其他窗口打开时,
// 通常在应用程序中重新创建一个窗口。
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. 也可以拆分成几个文件,然后用 require 导入。
2.编写 index.html 文件。
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
We are using node <script>document.write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
</body>
</html>
运行
打开你的命令行工具,然后从该文件夹运行 npm start 。然后你就能看见自己的应用程序了!
以样例为演示:
补充
所有演示均是在已经安装并配置好了 Node.js 的情况下进行的!如果不明白怎么安装可以参考这篇文章中的前半部分。
原创说明
转载请务必注明出处!
作者:SeaFever
原文链接:https://www.cnblogs.com/seafever/p/12400371.html