Electron环境搭建及HelloWorld

Electron环境搭建及HelloWorld

安装Electron

安装nodejs

安装Electron之前需要安装nodejs,访问官网https://nodejs.org,建议下载LTS版本并安装

在命令行输入以下命令,如果出现版本号则安装成功

node -v
npm -v

使用cnpm

国内因为网络问题npm安装较慢,所以我们改用淘宝源的cnpm(Linux环境下可能要在前面加sudo)

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

Electron安装

全局安装(Linux环境下可能要在前面加sudo)

cnpm install -g electron

如果仅仅是在项目内使用electron的话则需要在项目文件夹下执行以下命令(如果你不懂则可忽略此项目)

cnpm install electron

VSCode环境搭建

去微软官网https://visualstudio.microsoft.com/zh-hans/下载VSCode并安装

创建项目文件目录,并用VSCode打开项目文件夹

右键VSCode的资源管理器,然后点击在集成终端中打开,下方会弹出终端

执行命令

 cnpm init --yes

我们看到会在目录下生成一个package.json文件,其内容大致如下

{
  "name": "test03",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

一般我们将main字段的index.js改成main.js

{
  "name": "test03",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

然后创建main.js文件与index.html文件

touch main.js
touch index.html

HelloWorld

VSCode中打开index.html

输入英文感叹号并敲击Tab键即可生成html模板。在body标签下写如hello,world

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    hello,world
</body>
</html>

在main.js写入如下代码

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

//app启动后创建窗口
app.whenReady().then(() => {
    const mainWin = new BrowserWindow({
        width: 600,		//窗口宽
        height: 400		//窗口高
    })

    //加载html
    mainWin.loadFile('index.html')

    //监听关闭事件
    mainWin.on('close', () => {
        console.log('close.....')
    })
    app.on('window-all-closed', () => {
        console.log('all window is closed')
        app.quit()
    })
})

保存后在VSCode中的集成终端中执行启动命令,即可看到窗口了

electron .
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值