win10配置Electron安装环境以及解决报错

学习electron做桌面应用程序开发,从安装到Hellow World,过程中遇到的问题以及解决方式。

开始学习

这边Electron官方文档有详细的步骤。

基本要求

检查 Node.js 是否正确安装,请在您的终端输入以下命令:

node -v
npm -v

创建程序

Electron 应用程序遵循与其他 Node.js 项目相同的结构。首先创建一个文件夹并初始化 npm 包。

mkdir my-electron-app && cd my-electron-app
npm init

有几条规则需要遵循:

  • entry point 应为 main.js
  • authordescription 可为任意值,但对于应用打包是必填项

你的 package.json 文件应该像这样:

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "Hello World!",
  "main": "main.js",
  "author": "Jane Doe",
  "license": "MIT"
}

然后,将 electron 包安装到应用的开发依赖中。

npm install --save-dev electron

好了,走到这一步开始出现问题!!!

image

read ECONNRESET以及electron@25.0.1 postinstall: `node install.js` 应该是表达安装失败了,开始各种百度怎么解决问题。

将electron下载地址指向taobao镜像:

npm config set electron_mirror "https://npm.taobao.org/mirrors/electron/"

等同于在~/.npmrc添加:

electron_mirror="https://npm.taobao.org/mirrors/electron/"

上面两种方式达到同样的效果,任选一种即可。
然后删了\node_modules\electron文件夹,或者删了整个\node_modules来尝试重新执行npm install --save-dev electron,这次没有报错

image

接着看文档,在package.json配置文件中的scripts字段下增加一条start命令:

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

在项目的根目录下创建一个名为main.js的空文件,添加代码

const { app, BrowserWindow } = require('electron')
// 需在当前文件内开头引入 Node.js 的 'path' 模块
const path = require('path')

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })

    win.loadFile('index.html')
}

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

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

创建preload.js,输出Electron的版本号和依赖项到web页面上

window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
        const element = document.getElementById(selector)
        if (element) element.innerText = text
    }

    for (const dependency of ['chrome', 'node', 'electron']) {
        replaceText(`${dependency}-version`, process.versions[dependency])
    }
})

创建index.html,添加代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>你好!</title>
  </head>
  <body>
    <h1>你好!</h1>
    我们正在使用 Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    和 Electron <span id="electron-version"></span>.
  </body>
</html>

执行start

npm start

又出错了!!!

image

它意思应该是让我重新安装,于是又开始百度,最终找到了解决问题的办法。

对比electron的版本后发现依赖中少了dist文件夹和path.txt文件

image

手动创建空文件夹和空文本,dist的文件夹的内容为Electron自行选择版本解压后的内容,path.txt中添加文本electron.exe

到此,重新在终端中执行npm start可以成功启动项目。

image

环境安装到此结束,其中也参考了大佬 涅槃快乐 对npm安装electron源码的深入解读
另外,本篇如有不足之处望指出。

posted @ 2023-06-08 15:26  Phopen  阅读(845)  评论(0编辑  收藏  举报