应用已在 try/catch 内声明

app has already been declared within try/catch

我有以下 try/catch:

try {
    var { app } = require('electron').remote;
} catch (e) {
    var { app } = require('electron');
}

尽管它是有效的,但 ESLint 有一个问题表明 app 已经被声明。

所以,我尝试将 var 移到 try/catch 上方,但是 = 出错了,说它是一个 Unexpected token,就像这样:

var app;
try {
    { app } = require('electron').remote;
} catch (e) {
    { app } = require('electron');
}

这样做的正确方法是什么,这样 ESLint 就不会抱怨?

var 在当前函数的范围内声明一个值。 try 语句不会创建那种范围,因此您在初始代码中是 re-declaring app。这就是为什么它没有通过 linting。

如果 app 仅在 trycatch 块内需要,您可以使用 let 而不是 var

首先,由于您明显使用的是 ES2015+(又名 "ES6+"),请考虑使用 letconst 而不是 varvar 在 ES2015+ 世界中基本上没有用。 (但以下两项也适用于 var。)

解析问题是因为{看起来像一个块的开头。您可以将整个作业包装在 () 中以解决这个问题:

let app;
try {
    ({ app } = require('electron').remote);
} catch (e) {
    ({ app } = require('electron'));
}

示例(伪装 require):

// fake require
function require(name) {
  return {app: {name: "I'm the app"}};
}

let app;
try {
  ({ app } = require('electon').remote);
} catch (e) {
  ({ app } = require('electron'));
}
console.log(app);

或者根本不使用解构:

let app;
try {
    app = require('electron').remote.app;
} catch (e) {
    app = require('electron').app;
}

// fake require
function require(name) {
  return {app: {name: "I'm the app"}};
}

let app;
try {
  app = require('electron').remote.app;
} catch (e) {
  app = require('electron').app;
}
console.log(app);