是否提升了 ES6 模块导入? [英] Are ES6 module imports hoisted?

查看:19
本文介绍了是否提升了 ES6 模块导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在新的 ES6 模块语法中,JavaScript 引擎不必评估代码来了解所有的导入/导出,它只会解析它并知道"要加载什么.

I know that in the new ES6 module syntax, the JavaScript engine will not have to evaluate the code to know about all the imports/exports, it will only parse it and "know" what to load.

这听起来像是在吊装.ES6 模块被吊起了吗?如果是这样,它们会在运行代码之前全部加载吗?

This sounds like hoisting. Are the ES6 modules hoisted? And if so, will they all be loaded before running the code?

这个代码可以吗?

import myFunc1 from 'externalModule1';

myFunc2();

if (Math.random()>0.5) {
    import myFunc2 from 'externalModule2';
}

推荐答案

经过更多研究,我发现:

After doing some more research, I've found:

  • 进口量增加了!根据规范ModuleDeclarationInstantiation
  • 在运行任何代码之前,将加载所有依赖模块.

此代码没有错误,并且可以正常工作:

This code will have no errors, and will work:

localFunc();

import {myFunc1} from 'mymodule';

function localFunc() { // localFunc is hoisted
    myFunc1();
}

这篇关于是否提升了 ES6 模块导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆