下载地址:https://nodejs.org/zh-cn/download/
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install -g 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({
width: 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 lang="en">
<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({
????????width:?1024,
????????height:?640,
????????transparent:?false,
????????frame:?true,
????????icon:?ico,
????????resizable:?true?//固定大小
????});
打开VSCODE的调试窗口,添加调试配置文件(nodejs)
{
????//?使用?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,这个协议导致不进入断点
????????}
????]
}
原文:https://www.cnblogs.com/songhaipeng/p/12857912.html