使用 cnpm 安装 Electron
转自:使用 cnpm 安装 Electron,才是正确快速的方法-CSDN博客
1. 使用 npm 安装 Electron
步骤 1: 初始化项目
在你的项目目录中初始化一个新的 Node.js 项目:
npm init -y
步骤 2: 安装 Electron
将 Electron 安装为开发依赖项:
npm install electron --save-dev
步骤 3: 验证安装
检查已安装的 Electron 版本:
npx electron -v
步骤 4: 创建主进程文件 main.js
在项目根目录下创建一个 main.js 文件,内容如下:
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
步骤 5: 创建 HTML 文件 index.html
在项目根目录下创建一个 index.html 文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
</body>
</html>
步骤 6: 修改 package.json
确保 package.json 中的 scripts 部分包含启动脚本:
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^33.2.0"
}
}
步骤 7: 运行应用
在项目根目录下运行以下命令来启动你的 Electron 应用:
npm start
2. 使用 cnpm 安装 Electron
步骤 1: 安装 cnpm
首先,安装 cnpm 以使用淘宝的 npm 镜像:
npm install -g cnpm --registry=https://registry.npmmirror.com
步骤 2: 初始化项目
在你的项目目录中初始化一个新的 Node.js 项目:
cnpm init -y
步骤 3: 安装 Electron
将 Electron 安装为开发依赖项:
cnpm install electron --save-dev
步骤 4: 验证安装
检查已安装的 Electron 版本:
npx electron -v
步骤 5: 创建主进程文件 main.js
在项目根目录下创建一个 main.js 文件,内容如下:
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
步骤 6: 创建 HTML 文件 index.html
在项目根目录下创建一个 index.html 文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<title>My Electron App</title>
</head>
<body>
<h1>Hello, Electron!</h1>
</body>
</html>
步骤 7: 修改 package.json
确保 package.json 中的 scripts 部分包含启动脚本:
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^33.2.0"
}
}
步骤 8: 运行应用
在项目根目录下运行以下命令来启动你的 Electron 应用:
cnpm run start
常见问题及解决方法
-
网络问题:
- 确保你的网络连接是稳定的。
- 尝试使用淘宝的 npm 镜像(cnpm)。
-
缓存问题:
- 清理 npm 缓存:
npm cache clean --force -
权限问题:
- 以管理员身份运行命令提示符或终端:
- Windows:右键点击命令提示符图标并选择“以管理员身份运行”。
- macOS 或 Linux:在命令前加上
sudo,例如:
sudo npm install electron --save-dev -
磁盘空间不足:
- 确保你的磁盘有足够的空间来完成安装。
-
详细错误信息:
- 获取更详细的错误信息:
npm start --verbose

浙公网安备 33010602011771号