按照electron官方文档,开始了打造你的第一个 Electron 应用
index.js,index.html,package.json一切都准备就绪,然后敲下了命令
npm run start
然后报错了。。报错信息如下
> your-app@1.0.0 start F:\work\front-end\electron\demo
> electron .
F:\work\front-end\electron\demo\node_modules\electron\index.js:14
throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
^
Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
at getElectronPath (F:\work\front-end\electron\demo\node_modules\electron\index.js:14:11)
at Object.<anonymous> (F:\work\front-end\electron\demo\node_modules\electron\index.js:18:18)
at Module._compile (internal/modules/cjs/loader.js:774:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
at Module.load (internal/modules/cjs/loader.js:641:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:681:19)
at require (internal/modules/cjs/helpers.js:16:16)
at Object.<anonymous> (F:\work\front-end\electron\demo\node_modules\electron\cli.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:774:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! your-app@1.0.0 start: `electron .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the your-app@1.0.0 start 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! C:\Users\admin\AppData\Roaming\npm-cache\_logs\2019-12-27T09_00_14_091Z-debug.log
纳尼,第一个应用就身先士卒了?!!那怎么继续下去?
于是我打开了报错的代码,如下
var fs = require('fs')
var path = require('path')
var pathFile = path.join(__dirname, 'path.txt')
function getElectronPath () {
if (fs.existsSync(pathFile)) {
var executablePath = fs.readFileSync(pathFile, 'utf-8')
if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
return path.join(process.env.ELECTRON_OVERRIDE_DIST_PATH, executablePath)
}
return path.join(__dirname, 'dist', executablePath)
} else {
throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
}
}
module.exports = getElectronPath()
可以看出是因为没有找到 path.txt 文件,我看了下目录,果然没有这个文件,那这个文件是本来就有的么,我去github查了一下,github上也没有啊,在源码搜了一下,发现在 install.js 中有创建这个文件,那这个install.js是什么时候运行的呢,我们来看下package.json,发现script中有个postinstall命令,这个命令是指装完包运行,所以是装完包运行这个命令报错了?
我们进这个目录运行下命令 node install
,发现报错如下
PS F:\work\front-end\electron\electron-quick-start\node_modules\electron> node install
(node:10024) UnhandledPromiseRejectionWarning: Error: EPERM: operation not permitted, lstat 'C:\Users\LIUXIU~1\AppData\Local\Temp\electron-download-CEvWd4\electron-v7.1.7-win32-x64.zip'
(node:10024) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting
a promise which was not handled with .catch(). (rejection id: 1)
(node:10024) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
嗯?怎么没有权限?赶紧用管理员权限打开命令行,运行上面的命令,还是一样的报错。。
继续输入命令 npm config ls -l
,输出以下内容
tmp = "C:\\Users\\admin\\AppData\\Local\\Temp"
tmp为npm安装模块时的临时目录,若该目录有权限问题,则npm在安装其他模块时,也会报出operation not permitted错误,npm可正常安装其他模块,故可排除目录权限的问题
让我们仔细看下代码
downloadArtifact({
version,
artifactName: 'electron',
force: process.env.force_no_cache === 'true',
cacheRoot: process.env.electron_config_cache,
platform: process.env.npm_config_platform || process.platform,
arch: process.env.npm_config_arch || process.arch
}).then((zipPath) => extractFile(zipPath)).catch((err) => onerror(err))
可以看到如下下载异常会抛出错误,继续看 downloadArtifact
这个方法,可以看到有个输出url的地方
function downloadArtifact(_artifactDetails) {
return __awaiter(this, void 0, void 0, function () {
var artifactDetails, fileName, url, cache, cachedPath;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
artifactDetails = _artifactDetails.isGeneric
? __assign({}, _artifactDetails) : __assign({ platform: process.platform, arch: utils_1.getHostArch() }, _artifactDetails);
utils_1.ensureIsTruthyString(artifactDetails, 'version');
artifactDetails.version = utils_1.normalizeVersion(artifactDetails.version);
fileName = artifact_utils_1.getArtifactFileName(artifactDetails);
url = artifact_utils_1.getArtifactRemoteURL(artifactDetails);
cache = new Cache_1.Cache(artifactDetails.cacheRoot);
if (!!artifactDetails.force) return [3 /*break*/, 2];
d("Checking the cache for " + fileName + " (" + url + ")");
return [4 /*yield*/, cache.getPathForFileInCache(url, fileName)];
把这里的url输出看看,url值如下
https://github.com/electron/electron/releases/download/v7.1.7/electron-v7.1.7-win32-x64.zip
把这个url放到浏览器回车,发现国内从github上下载东西极慢,所以之前npm i 的时候,就会一直卡在electron执行node install.js那里,最后因为超时导致安装依赖失败,现在我们可以设置下环境变量改变这个url,可以看@electron/get/dist/cjs/artifact-utils.js
文件中的url的值会取环境变量的值
function mirrorVar(name, options, defaultValue) {
// Convert camelCase to camel_case for env var reading
var lowerName = name.replace(/([a-z])([A-Z])/g, function (_, a, b) { return a + "_" + b; }).toLowerCase();
return (process.env["NPM_CONFIG_ELECTRON_" + lowerName.toUpperCase()] ||
process.env["npm_config_electron_" + lowerName] ||
process.env["npm_package_config_electron_" + lowerName] ||
process.env["ELECTRON_" + lowerName.toUpperCase()] ||
options[name] ||
defaultValue);
}
function getArtifactRemoteURL(details) {
var opts = details.mirrorOptions || {};
var base = mirrorVar('mirror', opts, BASE_URL);
if (details.version.includes('nightly')) {
base = mirrorVar('nightly_mirror', opts, NIGHTLY_BASE_URL);
}
var path = mirrorVar('customDir', opts, details.version);
var file = mirrorVar('customFilename', opts, getArtifactFileName(details));
return "" + base + path + "/" + file;
}
在 electron-quick-start/package.json 的script中加上
"install": "set ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/&& node ./node_modules/electron/install.js",
运行npm run install
,还是报错,现在url输出的是https://npm.taobao.org/mirrors/electron/v7.1.7/electron-v7.1.7-win32-x64.zip
在浏览器打开,果然是404,这个url往前面几级翻一下,发现https://npm.taobao.org/mirrors/electron
是可以访问的,原来淘宝镜像上electron下的资源版本号前面都没有v,所以我们要把url改为https://npm.taobao.org/mirrors/electron/7.1.7/electron-v7.1.7-win32-x64.zip才
可以下载zip包,要解决这个问题需要改下代码,在@electron/get/dist/cjs/artifact-utils.js
文件的getArtifactRemoteURL
方法中path后面添加一句
path = path.replace("v","");
重新运行npm run install
,成功安装~
运行npm run start
,成功启动electron应用~