项目文件结构
项目文件结构可以直接打开文件夹查看,也可以通过编译器查看(推荐用Visual Studio Code)。用VSCode打开项目后看到项目文件结构如下:
- node_modules:用于存放项目需要用到的依赖包等资源
- index.html:项目需要用到的一个html文件
- main.js:项目的主进程
- package.json:项目配置文件,用来编写对项目的配置
- 其他主要就是一些js文件(渲染进程)
程序
package.json
主要配置了项目名称、版本、描述、主进程文件、仓库地址、关键字、作者等信息,以及一个Debug。
其中比较重要的是主进程文件。通过"main":命令来配置,运行时将配置的主进程文件作为程序入口来运行。
Debug实质上是通过npm start命令行进行操作的。它定义了一个start命令,里面是“electron .”,表示在当前目录下执行electron命令,electron表示启动electron工程,点表示的是main命令下配置的文件,这个项目中就是main.js。
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
//const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
/*webPreferences: {
preload: path.join(__dirname, 'preload.js')
}*/
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// 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.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
const {app, BrowserWindow} = require(‘electron’)表示导入electron中的app和BrowserWindow;
app.whenReady().then(() => 后是项目在准备阶段时执行的方法,首先执行了createWindow()方法,然后是一个激活时间,如果BrowseWindow的数量不足一个,则执行createWindow方法;
在createWindow方法中,首先新建了一个BrowseWindow对象(即一个浏览窗口),然后这个对象导入一个index.html文件,填充进这个窗口中。
上一页
下一页