Electron——Electron的安装和简单使用

本文讲述了在Mac环境下安装Node.js和Electron过程中遇到的权限问题,通过npm和cnpm的使用,解决了下载和初始化过程中的错误,包括使用sudo、更换npm源和预装脚本的处理。最后介绍了创建并运行Electron应用的基本步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/120140142
本文出自【我是干勾鱼的博客

1 安装node.js

可以参考Mac环境下安装Node.js

2 安装npm

安装NPM。

3 安装electron

安装electron。

npm install --save-dev electron

报错:

$ npm install --save-dev electron

> core-js@3.17.2 postinstall /Users/yuhaidong/studying/electron/my-electron-app/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js:
> https://opencollective.com/core-js 
> https://patreon.com/zloirock 
> https://paypal.me/zloirock 
> bitcoin: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)


> electron@14.0.0 postinstall /Users/yuhaidong/studying/electron/my-electron-app/node_modules/electron
> node install.js

RequestError: read ETIMEDOUT
    at ClientRequest.<anonymous> (/Users/yuhaidong/studying/electron/my-electron-app/node_modules/got/source/request-as-event-emitter.js:178:14)
    at Object.onceWrapper (events.js:483:26)
    at ClientRequest.emit (events.js:388:22)
    at ClientRequest.origin.emit (/Users/yuhaidong/studying/electron/my-electron-app/node_modules/@szmarczak/http-timer/source/index.js:37:11)
    at TLSSocket.socketErrorListener (_http_client.js:475:9)
    at TLSSocket.emit (events.js:376:20)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)
npm WARN my-electron-app@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! electron@14.0.0 postinstall: `node install.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the electron@14.0.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/yuhaidong/.npm/_logs/2021-09-06T08_40_31_889Z-debug.log

参考解决Electron下载安装失败的问题

npm install -g cnpm --registry=https://registry.npm.taobao.org
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules'
npm ERR! }
npm ERR! 
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR! 
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/yuhaidong/.npm/_logs/2021-09-06T09_13_42_741Z-debug.log

Mac下命令权限问题,加入sudo:

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

结果如下:

$ npm install -g cnpm --registry=https://registry.npm.taobao.org
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules'
npm ERR! }
npm ERR! 
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR! 
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/yuhaidong/.npm/_logs/2021-09-06T09_13_42_741Z-debug.log
dashuaigedeMacBook:my-electron-app yuhaidong$ sudo npm install -g cnpm --registry=https://registry.npm.taobao.org
Password:
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext⸨       ░░░░░░░░░░░⸩ ⠦ extract:any-promise: sill extract any-promise@^1.3.0 ext/usr/local/bin/cnpm -> /usr/local/lib/node_modules/cnpm/bin/cnpm
+ cnpm@7.0.0
added 712 packages from 969 contributors in 72.296s

再次尝试安装electron,这回可以正常安装:

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

4 npm初始化

执行:

npm init

配置内容如下:

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "Hello World!",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Jane Doe",
  "license": "MIT",
  "devDependencies": {
    "electron": "^14.0.0"
  }
}

5 创建文件

main.js

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. 也可以拆分成几个文件,然后用 require 导入。

preload.js

// preload.js

// All of the Node.js APIs are available in the preload process.
// 它拥有与Chrome扩展一样的沙盒。
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

<!--index.html-->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-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>.

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

6 执行命令

执行命令:

npm start

弹出桌面界面:

在这里插入图片描述

如果要打开调试模式,则加入代码:

mainWindow.webContents.openDevTools()

即可,如图:

在这里插入图片描述

快捷键在macOS下是command + option + I,Windows下是Ctrl + Shift + I。

7 参考:

解决Electron下载安装失败的问题

npm和cnpm

Electron从零开始——介绍

Electron 文档

Electron从零开始——介绍

Mac环境下安装Node.js

打开调试模式

Electron 应用调试指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值