之前我们已经用html+css+js创建了一个项目,现在将这个项目用electron以应用程序呈现。
1,首先新建一个文件夹,从终端进入该文件夹:
2,在该文件夹下执行npm init,初始化该项目。
(主要要填写description、author和name等关键值,不填写的话后面打包会报错)
执行完毕,在该文件夹下会多出一个package.json文件。
3,然后在vscode(或其他编辑器)中打开该文件夹,安装electron:
npm install electron --save-dev 或 yarn add electron --dev,建议使用yarn。
如果安装electron报错:
RequestError: read ECONNRESET
具体解决方法如下:
- npm install electron 执行后, 当运行到node install.js时, 中断执行( windows cmd用ctrl+c)
- 进入 node_modules/electron文件下, 编辑install.js
- 修改downloadArtifact这段代码, 添加淘宝镜像地址
downloadArtifact({ version, artifactName: 'electron', force: process.env.force_no_cache === 'true', cacheRoot: process.env.electron_config_cache, checksums: process.env.electron_use_remote_checksums ? undefined : require('./checksums.json'), mirrorOptions:{
mirror:'https://cdn.npm.taobao.org/dist/electron/',
platform,
arch,
} }).then(extractFile).catch(err => { console.error(err.stack); process.exit(1); });
- 然后在当前目录 的cmd中执行 node install.js
4,打开package.json,将main的值修改为main.js
5,打开main.js:
const electron = require("electron"); const { app, ipcMain, BrowserWindow, screen } = electron; const path = require('path'); let win; let isMaximized = false; let size; app.on("ready", (e) => { size = screen.getPrimaryDisplay().workAreaSize; win = new BrowserWindow({ width: 1280, height: 800, resizable: false, frame: false, fullscreenable: true, backgroundColor: "transparent", webPreferences: { nodeIntegration: true, contextIsolation: false, preload: path.join(__dirname, './preload.js') }, }); app.setAppUserModelId("测试工具"); win.loadURL(__dirname + "/index.html"); win.show(); win.webContents.openDevTools({ mode: "detach" }); }); ipcMain.on("window-mini", () => { win.minimize(); }); ipcMain.on("window-toggleScreen", () => { isMaximized = !isMaximized; let h = isMaximized ? size.height : 800; let w = isMaximized ? size.width : 1280; win.setBounds({ height: h, width: w, x: Math.floor((size.width - w) / 2), y: Math.floor((size.height - h) / 2), }); }); ipcMain.on('window-close', () => { win.close(); win.destroy(); app.quit(); app.exit(); })
新窗体打开控制台:win.webContents.openDevTools({ mode: "detach" });
预加载文件:preload.js:
window.ipcRenderer = require('electron').ipcRenderer; window.shell = require('electron').shell; window.fs = require('fs'); window.path = require('path');,
6,在package.json中添加:
"scripts": { "start": "electron ." },
7,将html+css+js创建的项目复制到当前文件夹,运行npm start,启动electron应用程序: