Electron 创建桌面应用

Electron 创建桌面应用

添加淘宝 NPM 镜像

啥都不说了,干活前先添加淘宝 NPM 镜像,不然后面安装模块的时候会卡住。

$ sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

安装 electron

这里我是使用的全局

$ sudo cnpm install -g electron

创建应用

一个 Electron 应用的目录结构大致如下:

myapp/
├── package.json
├── main.js
└── index.html

package.json

{
  "name": "myapp",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "start": "electron main.js"
  }
}

main.js

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

let win;

function createWindow () {
  win = new BrowserWindow({width: 800, height: 600});

  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }));

  win.on('closed', () => {
    win = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <ul>
      <li>Node: <script>document.write(process.versions.node)</script></li>
      <li>Chrome: <script>document.write(process.versions.chrome)</script></li>
      <li>Electron: <script>document.write(process.versions.electron)</script></li>
    </ul>
  </body>
</html>

运行应用

进入应用程序目录,然后运行

$ electron .

另外,由于我们在 package.json 文件里定义了

  ...
  "scripts": {
    "start": "electron main.js"
  }

所以也可以使用 npm 来运行

$ npm install
$ npm start
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值