Electron failed to install correctly, please delete node_modules/electron and try installing again

Electron 手动下载安装指南

问题描述

Electron 安装失败,提示 “Electron failed to install correctly”

解决方案

方案一:使用国内镜像源

  1. 设置环境变量

    # 在PowerShell中执行
    $env:ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
    $env:ELECTRON_CUSTOM_DIR="{{ version }}"
    
  2. 重新安装

    pnpm remove electron
    pnpm add electron@27.3.11 --save-dev
    

方案二:手动下载二进制文件

  1. 下载 Electron 二进制文件

    • 访问:https://github.com/electron/electron/releases/tag/v27.3.11
    • 下载:electron-v27.3.11-win32-x64.zip
  2. 创建目标目录

    node_modules\.pnpm\electron@27.3.11\node_modules\electron\dist\
    
  3. 解压文件

    • 将下载的 zip 文件解压到上述目录
    • 确保 electron.exedist 文件夹中
  4. 验证安装

    npm start
    

方案三:使用 npm 替代 pnpm

如果 pnpm 持续有问题,可以切换到 npm:

  1. 删除 pnpm 相关文件

    Remove-Item -Recurse -Force node_modules
    Remove-Item pnpm-lock.yaml
    
  2. 使用 npm 安装

    npm install
    npm start
    

方案四:修改 package.json 使用本地 Electron

  1. 全局安装 Electron

    npm install -g electron
    
  2. 修改启动脚本
    将 package.json 中的启动脚本改为:

    {
      "scripts": {
        "start": "electron .",
        "dev": "electron . --dev"
      }
    }
    

文件结构检查

安装成功后,应该有以下文件结构:

node_modules/
└── .pnpm/
    └── electron@27.3.11/
        └── node_modules/
            └── electron/
                ├── dist/
                │   ├── electron.exe
                │   ├── resources/
                │   └── ...
                ├── index.js
                └── package.json

常见问题

Q: 下载速度很慢或失败

A: 使用国内镜像源或 VPN

Q: 权限问题

A: 以管理员身份运行 PowerShell

Q: 防火墙阻止

A: 临时关闭防火墙或添加例外

Q: 网络代理问题

A: 配置 npm 代理设置

npm config set proxy http://proxy-server:port
npm config set https-proxy http://proxy-server:port

验证命令

# 检查Electron版本
npx electron --version

# 检查文件是否存在
dir "node_modules\.pnpm\electron@27.3.11\node_modules\electron\dist\electron.exe"

脚本 fix-electron.js

const fs = require("fs");
const path = require("path");
const https = require("https");
const { execSync } = require("child_process");

console.log("🔧 修复Electron安装...\n");

// 设置镜像源
process.env.ELECTRON_MIRROR = "https://npmmirror.com/mirrors/electron/";
process.env.ELECTRON_CUSTOM_DIR = "{{ version }}";

console.log("📡 使用镜像源:", process.env.ELECTRON_MIRROR);

// 检查Electron是否正确安装
function checkElectronInstallation() {
  const electronPath = path.join(
    __dirname,
    "node_modules",
    ".pnpm",
    "electron@27.3.11",
    "node_modules",
    "electron",
    "dist",
    "electron.exe"
  );
  return fs.existsSync(electronPath);
}

// 下载文件
function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    console.log(`📥 下载: ${url}`);
    const file = fs.createWriteStream(dest);

    https
      .get(url, (response) => {
        if (response.statusCode === 302 || response.statusCode === 301) {
          // 处理重定向
          return downloadFile(response.headers.location, dest)
            .then(resolve)
            .catch(reject);
        }

        if (response.statusCode !== 200) {
          reject(new Error(`下载失败: ${response.statusCode}`));
          return;
        }

        const totalSize = parseInt(response.headers["content-length"], 10);
        let downloadedSize = 0;

        response.on("data", (chunk) => {
          downloadedSize += chunk.length;
          const progress = ((downloadedSize / totalSize) * 100).toFixed(1);
          process.stdout.write(`\r进度: ${progress}%`);
        });

        response.pipe(file);

        file.on("finish", () => {
          file.close();
          console.log("\n✅ 下载完成");
          resolve();
        });

        file.on("error", (err) => {
          fs.unlink(dest, () => {});
          reject(err);
        });
      })
      .on("error", reject);
  });
}

// 解压zip文件 (简单实现)
function extractZip(zipPath, extractPath) {
  try {
    // 使用PowerShell解压
    const command = `powershell -command "Expand-Archive -Path '${zipPath}' -DestinationPath '${extractPath}' -Force"`;
    execSync(command, { stdio: "inherit" });
    console.log("✅ 解压完成");
    return true;
  } catch (error) {
    console.error("❌ 解压失败:", error.message);
    return false;
  }
}

async function fixElectron() {
  try {
    // 1. 检查当前安装状态
    console.log("🔍 检查Electron安装状态...");
    if (checkElectronInstallation()) {
      console.log("✅ Electron已正确安装");
      return;
    }

    // 2. 尝试重新安装
    console.log("🔄 尝试重新安装Electron...");
    try {
      execSync("pnpm remove electron", { stdio: "inherit" });
      execSync("pnpm add electron@27.3.11 --save-dev", { stdio: "inherit" });

      if (checkElectronInstallation()) {
        console.log("✅ Electron重新安装成功");
        return;
      }
    } catch (error) {
      console.log("⚠️ 自动安装失败,尝试手动下载...");
    }

    // 3. 手动下载
    const electronDir = path.join(
      __dirname,
      "node_modules",
      ".pnpm",
      "electron@27.3.11",
      "node_modules",
      "electron"
    );
    const distDir = path.join(electronDir, "dist");
    const zipPath = path.join(__dirname, "electron-v27.3.11-win32-x64.zip");

    // 创建目录
    fs.mkdirSync(distDir, { recursive: true });

    // 下载Electron
    const downloadUrl =
      "https://github.com/electron/electron/releases/download/v27.3.11/electron-v27.3.11-win32-x64.zip";
    await downloadFile(downloadUrl, zipPath);

    // 解压
    console.log("📦 解压Electron...");
    if (extractZip(zipPath, distDir)) {
      // 清理下载文件
      fs.unlinkSync(zipPath);

      // 验证安装
      if (checkElectronInstallation()) {
        console.log("🎉 Electron手动安装成功!");
      } else {
        console.log("❌ 安装验证失败");
      }
    }
  } catch (error) {
    console.error("❌ 修复失败:", error.message);
    console.log("\n📖 请参考 manual-download-guide.md 进行手动操作");
  }
}

// 运行修复
fixElectron();

运行 node fix-electron.js
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值