Electron入门——开发环境搭建

版权声明: https://blog.csdn.net/GISuuser/article/details/86678960

Electron这个框架听起来非常的厉害,可以用JS开发跨平台的应用,最近也来试一试,如果真的像宣传的那样还是非常厉害的。网上的其他的搭建环境都是让全局安装electron和electron-prebuilt模块,这里楼主自己在局部搭建了一下,没有使用全局模块,运行命令也简化了,创建三个文件就可以了。

首先在一个空的文件内,创建package.json文件

{
  "name": "electronl",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": ".\\node_modules\\.bin\\electron .",
	"start": "chcp 65001 && npm test"
  },
  "author": "hanbo",
  "license": "ISC",
  "dependencies": {
    "electron": "^4.0.2"
  },
  "devDependencies": {
    "electron-prebuilt": "^1.4.13"
  }
}

然后创建index.js



const { app, Menu ,BrowserWindow} = require('electron');


// 保持一个对于 window 对象的全局引用,不然,当 JavaScript 被 GC,
// window 会被自动地关闭
let mainWindow = null;
//设置菜单
let dockMenu = Menu.buildFromTemplate([
    {
        label: '文件', click: function () {
            console.log('点击事件');
        }
    },
    {
        label: '编辑', submenu: [
            {label: '保存'},
            {label: '另存'}
        ]
    },
    {label: '帮助'}
]);
Menu.setApplicationMenu(dockMenu);

// 当所有窗口被关闭了,退出。
app.on('window-all-closed', function () {
    // 在 OS X 上,通常用户在明确地按下 Cmd + Q 之前
    // 应用会保持活动状态
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// 当 Electron 完成了初始化并且准备创建浏览器窗口的时候
// 这个方法就被调用
app.on('ready', function () {
    // 创建浏览器窗口。
    mainWindow = new BrowserWindow({
        width: 800, height: 600,
        webPreferences: {
            nodeIntegrationInWorker: true//支持多线程
        }
    });
    // 加载应用的 index.html
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // 打开开发工具
    mainWindow.openDevTools();

    // 当 window 被关闭,这个事件会被发出
    mainWindow.on('closed', function () {
        // 取消引用 window 对象,如果你的应用支持多窗口的话,
        // 通常会把多个 window 对象存放在一个数组里面,
        // 但这次不是。
        mainWindow = null;
    });
});

然后创建index.html

<!DOCTYPE html>
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using io.js <script>document.write(process.version)</script>
and Electron <script>document.write(process.versions['electron'])</script>.
</body>
</html>

到这里就创建完了,第一运行的时候先npm install或者cnpm intsall安装所需模块

然后运行npm start项目就跑起来了效果图如下:

 

猜你喜欢

转载自blog.csdn.net/GISuuser/article/details/86678960