• Electron -- 编写第一个Eletron程序


    编写第一个eletron程序

    1. 安装

    npm install --save-dev electron
    
    • 1

    当你安装完electron后,你会发现你的项目目录下多了一个node_modules文件夹,里面有electron的相关文件。
    在安装完之后,我们需要手动的去到package.json文件中添加一下启动的配置:

    {
      "scripts": {
        "start": "electron ."
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    完整的配置如下:

    {
      "name": "my-electron-app", //我的项目名称
      "version": "1.0.0",
      "main": "index.js", // 入口文件
      "scripts": {
     "start": "electron .",  // 启动脚本 
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "description": "",
      "devDependencies": {
        "electron": "^20.1.2"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2. 创建一个简单的html页面并且用eletron打开

    在项目任意一个目录下创建一个html文件:

    DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        
        <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
        <title>Hello World!title>
      head>
      <body>
        <h1>Hello World!h1>
        We are using Node.js <span id="node-version">span>,
        Chromium <span id="chrome-version">span>,
        and Electron <span id="electron-version">span>.
      body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    根据默认的入口文件配置,我们还需要在根目录下创建一个index.js文件,用来作为整个程序的启动文件

    // 加载必要的模块
    const {app, BrowserWindow} = require('electron')
    
    const createWindow = () => {
        const win = new BrowserWindow({
            width: 800,
            height: 600
        })
    
        // 加载我们刚刚创建的html文件,由于我是在src目录下创建的,所以这边使用更多是相对路径
        win.loadFile('./src/index.html')
    }
    
    app.whenReady().then(() => {
        // 创建窗口
        createWindow()
        app.on('activate', () => {
            if (BrowserWindow.getAllWindows().length === 0) createWindow()
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3. 运行

    npm run start
    
    • 1

    此时就可以看到页面上显示出我们的第一个页面了

    4. 打包

    添加必要的依赖

    npm install --save-dev @electron-forge/cli
    npx electron-forge import
    
    • 1
    • 2

    打包程序

    npm run make
    
    • 1

    此时我们的程序就会出现在out目录下, 直接运行out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app就可以运行我们的程序了

  • 相关阅读:
    神经网络控制器设计步骤,神经网络控制系统设计
    关于 K8s 的一些基础概念整理
    自学考试到底难不难?
    2023最新计算机信息管理毕设选题分享
    FineReport智能表格软件-JS实现大数据集导出(一)
    LeetCode 164. 最大间距
    HVV(护网)蓝队视角的技战法分析
    设计模式浅析(八) ·外观模式
    20年将投资美国约2000亿美元,三星电子财大气粗的样子真好看
    RabbitMQ3.10.7高级特性
  • 原文地址:https://blog.csdn.net/weixin_43943642/article/details/126802175