Electron是使用JavaScript,HTML和CSS构建跨平台的桌面应用程序框架。VSCode下可使用Electron调试代码。
安装nodejs
到https://nodejs.org/zh-cn/download/ 下载并安装nodejs。
注册npm镜像
输入命令:npm install -g cnpm --registry=https://registry.npm.taobao.org
安装Electron
输入命令:cnpm install -g electron
新建配置Electron项目
新建项目目录
mkdir eledemo
进入目录
cd eledemo
初始化项目,创建package.json
npm init -y
使用VSCode打开项目文件夹
code .
VSCode中无法使用cnpm需要使用PowerShell进行授权
执行set-ExecutionPolicy RemoteSigned命令,然后选A
添加electron依赖
cnpm install electron -S
修改package.json
{
"name": "eledemo",
"version": "1.0.0",
"description": "This is an electron demo project.",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^8.2.5"
}
}
新建main.js文件
const electron = require('electron');
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
1024.
height: 640.
transparent: false,
frame: true,
resizable : true //固定大小
});
const URL = url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
})
mainWindow.loadURL(URL);
console.log(URL);
mainWindow.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X 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 OS X 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();
}
});
新建index.html文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> hello! This is an electron project. </body> </html>
运行项目
cnpm install
npm start
添加应用图标文件logo.png
修改main.js文件
function createWindow() {
var ico = path.join(__dirname, 'img', 'logo-28.png');
// Create the browser window.
mainWindow = new BrowserWindow({
1024.
height: 640.
transparent: false,
frame: true,
icon: ico,
resizable: true //固定大小
});
VSCode调试Electron项目
打开VSCode左侧的调试按钮打开调试配置面板,然后点击“自定义运行和调试创建launch.json文件”,若出现选择下拉框,则选择“Node.js调试器”。
项目文件夹中的.vscode文件夹中就会多一个文件launch.js,修改该文件代码:
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "configurations": [ {
"type": "node",
"request": "launch",
"name": "Electron Main",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"program": "${workspaceFolder}/main.js",
"protocol": "inspector" //添加默认的协议是legacy,这个协议导致不进入断点
} ] }