Javascript 浏览器:标识符 X 已被声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36140252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:41:22  来源:igfitidea点击:

Browser: Identifier X has already been declared

javascriptecmascript-6

提问by Non

I am using ES6 with Babel in my project and I am getting an error when I declare one of my const

我在我的项目中使用 ES6 和 Babel,当我声明我的一个时出现错误 const

'use strict';

const APP = window.APP = window.APP || {};
const _ = window._;

APP.personalCard = (function () {

   ...

}());

the error

错误

Uncaught TypeError: Identifier 'APP' has already been declared

未捕获的类型错误:已声明标识符“APP”

and that is the whole file, I don't have that declare anywhere else in that file. But I have declared that var in the top of the other files.

这就是整个文件,我没有在该文件的其他任何地方声明。但是我已经在其他文件的顶部声明了 var 。

What do you think it should be ?

你认为它应该是什么?

回答by Bergi

But I have declared that var in the top of the other files.

但是我已经在其他文件的顶部声明了 var 。

That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const.

那就是问题所在。毕竟,这会在同一个(全局)范围内对同一个名称进行多次声明——这将抛出一个错误const

Instead, use var, use only one declaration in your main file, or only assign to window.APPexclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.

相反,使用var,仅在主文件中使用一个声明,或仅分配给window.APP独占。
或者立即使用 ES6 模块,让你的模块打包器/加载器按预期处理暴露它们。

回答by sambua

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

我有一个非常接近的问题,但就我而言,它是Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... }where letter eis generated via minifier (uglifier).

在我的情况下,因为使用try {} catch (e) { var e = ... }where 字母e是通过 minifier (uglifier) 生成的。

So better solution could be use catch(ex){}(exas an Excemption)

因此可以使用更好的解决方案catch(ex){}ex作为Excemption

Hope somebody who searched with the similar question could find this question helpful.

希望搜索过类似问题的人会发现这个问题很有帮助。

回答by slezica

Remember that windowis the global namespace. These two lines attempt to declare the same variable:

请记住,这window是全局命名空间。这两行试图声明相同的变量:

window.APP = { ... }
const APP = window.APP

The second definition is not allowed in strictmode (enabled with 'use strict'at the top of your file).

strict模式中不允许使用第二个定义('use strict'在文件顶部启用)。

To fix the problem, simply remove the const APP =declaration. The variable will still be accessible, as it belongs to the global namespace.

要解决此问题,只需删除const APP =声明即可。该变量仍然可以访问,因为它属于全局命名空间。