Javascript 导入已定义的const-won';t型投掷错误
我有一个加载两个脚本的html文件:Javascript 导入已定义的const-won';t型投掷错误,javascript,google-chrome-extension,ecmascript-6,firefox-addon-webextensions,es6-modules,Javascript,Google Chrome Extension,Ecmascript 6,Firefox Addon Webextensions,Es6 Modules,我有一个加载两个脚本的html文件:utils.js和background.js 在utils.js中,我定义了: const test = 'a'; 在background.js中,我有: import {test} from "./modules/hosts.js"; // no error here console.log(test); // 'b' is printed 模块hosts.js定义: const test = 'b';
utils.js
和background.js
在utils.js
中,我定义了:
const test = 'a';
在background.js
中,我有:
import {test} from "./modules/hosts.js"; // no error here
console.log(test); // 'b' is printed
模块hosts.js
定义:
const test = 'b';
我预计导入会失败,因为已经定义了test
,但它可以工作,test
被host.js
模块的值重载。它为什么有效? 编辑:
HTML文件:
<script type="application/javascript" src="utils/utils.js"></script>
<script type="module" src="background.js"></script>
@wOxxOm很抱歉丢失了信息。。。下次我将尝试构建MCVE。我添加了一段html代码,您可以看到utils.js
没有作为模块加载。另外,当我注释掉import
行时,它将按预期打印“a”。啊,background.js作为一个模块加载,因此它的词法环境不同于utils.js所在的全局环境。每个模块都有自己的名称空间,这是模块的优点之一。@wOxxOm我现在看到了,我甚至可以在background.js
中创建相同的const
,而且不会失败。这是一件很好的事情!非常感谢。