Electron之初体验

Electron是一款使用HtmlCssJS开发跨平台桌面应用的框架。

话不多说直接开搞。

必坑指南:

  • node版本>=18.0

  • 使用淘宝镜像安装npm相关包;

  • 把下面两行配置放到你的npmrc文件中

    复制代码
    electron_mirror=https://npm.taobao.org/mirrors/electron/
    ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/

创建项目

使用下面命令创建一个空项目

shell 复制代码
mkdir electron-demo && cd electron-demo
npm init

安装electron依赖包,等待安装完成

shell 复制代码
cnpm install --save-dev electron

写代码

创建index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1 id="hello"></h1>
</body>
</html>

创建preload.js,会在应用加载渲染进程之前执行这个文件的代码

js 复制代码
// dom内容加载成功的监听
window.addEventListener('DOMContentLoaded', () => {
	// 加载页面成功之后设置元素的内容
    const element = document.getElementById('hello')
    element.innerText = 'Hello,Electron!'
})

创建main.js,整个项目的入口js文件

js 复制代码
const { app, BrowserWindow } = require('electron')
const {join} = require("path");

// 创建应用窗口
const createWindow = () => {
    const win = new BrowserWindow({
    	// 窗口尺寸
        width: 800,
        height: 600,
        webPreferences: {
        	// 设置渲染前执行的js文件
            preload: join(__dirname, 'preload.js')
        }
    })
    // 加载的html文件
    win.loadFile('index.html')
}

app.whenReady().then(() => {
    createWindow()
})

启动项目

修改package.json

设置入口js文件

json 复制代码
  "main": "main.js",

设置启动脚本

json 复制代码
  "scripts": {
    "start": "electron ."
  },

执行脚本

shell 复制代码
npm start

正常情况会出现下面这个窗口

相关推荐
KaMeidebaby4 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl5 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf5 小时前
Python 异常处理
前端·后端·python
sugar__salt6 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo6 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉6 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
小妖6666 小时前
js 生成随机数技巧 Math.random().toString(36)
javascript·随机数