1、创建工程文件夹 并进入
mkdir my-electron-app && cd my-electron-app
2、初始化npm
npm init -y
3、安装electron
npm i --save-dev electron
自动化脚本
#!/bin/bash
# -*- coding:utf-8 -*-
import os
import sys
import json
if (len(sys.argv) < 2 ):
print("缺少electron工程名字 ; python create-electron-app name")
exit(0)
CURRENT_PATH = sys.path[0]
APP_NAME = sys.argv[1]
APP_DIR = os.path.join(CURRENT_PATH,APP_NAME)
if os.path.exists( APP_DIR ):
print("目录" + APP_NAME + "已存在")
exit(0)
# 创建工程目录
os.system("cd {} && mkdir {}".format(CURRENT_PATH,APP_NAME))
# 初始化npm
os.system("cd {} && npm init -y".format(APP_DIR))
#安装electron
os.system("cd {} && npm i --save-dev electron".format(APP_DIR))
#创建主脚本
mainjs = """
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('main.html')
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
"""
fs = open(os.path.join(APP_DIR,"main.js"),"w")
fs.write(mainjs)
fs.close()
#创建主html
mainhtml = """
<OCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>世界你好</p>
</body>
</html>
"""
fs = open(os.path.join(APP_DIR,"main.html"),"w")
fs.write(mainhtml)
fs.close()
# 添加快捷启动方式
fs = open(os.path.join(APP_DIR,"package.json"),"r")
jsondata = fs.read()
fs.close()
jsonobj = json.loads(jsondata)
jsonobj["scripts"]["start"] = "electron ."
jsonobj["main"]= "main.js"
jsondata = json.dumps(jsonobj,indent=4)
fs = open(os.path.join(APP_DIR,"package.json"),"w")
fs.write(jsondata)
fs.close()
# 启动
os.system("cd {} && npm start".format(APP_DIR))