Electron-02-创建并运行helloworld项目
新建工作区
- 在F盘新建F:\Electron_WorkSpace用来存放项目目录
建立helloworld项目
- 建立F:\Electron_WorkSpace\helloworld目录并进入。
npm init
初始化项目:配置文件一路回车,我们暂不做配置,会新建一个package.json
npm install electron --save-dev
安装electron作为helloworld项目的依赖。此命令执行时间有点长,因为要安装很多的依赖文件。
可以看到目录下多了很多文件
编写代码
我们要关注的文件有三个
- package.json 通过
npm init
自动生成,需要修改 - index.js 自己创建一个主进程文件,需要些代码
- index.html 主窗口显示的页面,需要写代码
package.json修改"script"
{
"name": "helloworld",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^5.0.6"
}
}
修改为
{
"name": "helloworld",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"electron": "^5.0.6"
},
"devDependencies": {},
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC"
}
index.js
const electron = require("electron");
const url = require("url");
const path = require("path");
const {app, BrowserWindow} = electron;
let mainWindow;
//等待app准备好
app.on('ready', function() {
//创建新窗口
mainWindow = new BrowserWindow({});
//将html加载到窗口
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file",
slashes: true
}));
//当关闭窗口是退出app
mainWindow.on("closed", function() {
app.quit();
});
});
index.html
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
运行
npm start