最近学习一个node的开发工具, 用来跨平台做桌面应用的小应用Electron.
学习搭建环境.
操作系统: Ubuntu18, Win也可以(只是很久以前的事情了,最近一直没有碰windows了)
nodejs: v12.13.1
目标: 搭建一个初始化的Electron应用.
步骤如下:
step1:
terminal(cmd 在windows上)
cd ~ //进入到本用户目录下
mkdir electron-tests //创建一个实验项目目录
step2:
#初始化npm项目
npm init
# 添加electron的依赖.此步发现国内下载github上的electron编译包很费劲,直接去到淘宝镜像上去下.
# electron安装过程中的源码会用到
url = ELECTRON_MIRROR + ELECTRON_CUSTOM_DIR + ‘/‘ + ELECTRON_CUSTOM_FILENAME
# 我们就利用这里的 ELECTRON_MIRROR, 在环境变量中添加一个淘宝镜像地址: 在.bashrc或者.zshrc(我用的ozsh, 所以就配在这里了)
export ELECTRON_MIRROR="https://cdn.npm.taobao.org/dist/electron/";
# 然后进行安装 electron
npm install electron --save-dev
# 如果需要全局安装的话,就用
npm install -g electron
step3:
在目录中创建main.js, 用于npm start使用,和package.json中配置初始入口.
1 const electron = require(‘electron‘); 2 3 const { app, BrowserWindow } = electron; 4 5 function createWindow () { 6 // 创建浏览器窗口 7 const win = new BrowserWindow({ 8 width: 800, 9 height: 600, 10 webPreferences: { 11 nodeIntegration: true 12 } 13 }) 14 15 // 并且为你的应用加载index.html 16 win.loadFile(‘index.html‘) 17 18 // 打开开发者工具 19 win.webContents.openDevTools() 20 } 21 22 // This method will be called when Electron has finished 23 // initialization and is ready to create browser windows. 24 // 部分 API 在 ready 事件触发后才能使用。 25 app.whenReady().then(createWindow); 26 27 // Quit when all windows are closed. 28 app.on(‘window-all-closed‘, () => { 29 // 在 macOS 上,除非用户用 Cmd + Q 确定地退出, 30 // 否则绝大部分应用及其菜单栏会保持激活。 31 if (process.platform !== ‘darwin‘) { 32 app.quit() 33 } 34 }); 35 36 app.on(‘activate‘, () => { 37 // 在macOS上,当单击dock图标并且没有其他窗口打开时, 38 // 通常在应用程序中重新创建一个窗口。 39 if (BrowserWindow.getAllWindows().length === 0) { 40 createWindow() 41 } 42 });
在目录中创建index.html, 用户界面的展示所用.
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Hello World!</title> 6 <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag --> 7 <meta http-equiv="Content-Security-Policy" content="script-src ‘self‘ ‘unsafe-inline‘;" /> 8 </head> 9 <body> 10 <h1>Hello World!</h1> 11 We are using node <script>document.write(process.versions.node)</script>, 12 Chrome <script>document.write(process.versions.chrome)</script>, 13 and Electron <script>document.write(process.versions.electron)</script>. 14 </body> 15 </html>
step4:
看一下最后的package.json
1 { 2 "name": "batch_rename", 3 "version": "1.0.0", 4 "main": "main.js", 5 "license": "MIT", 6 "scripts": { 7 "start": "electron ." 8 }, 9 "dependencies": { 10 "electron": "^8.2.0", 11 "lodash": "^4.17.15"//这里可以不用的,因为以后可能会用到,就直接顺手安装的 12 } 13 }
step5:
启动命令
npm start
原文:https://www.cnblogs.com/jingyingggong/p/12635092.html