ES6模块进口是否悬挂? [英] Are ES6 module imports hoisted?

查看:104
本文介绍了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';
}


推荐答案

我发现:


  • 导入已被吊起!根据 > ModuleDeclarationInstantiation

  • 在运行任何代码之前,所有依赖模块都将被加载。

  • Imports ARE hoisted! according to the spec of ModuleDeclarationInstantiation
  • ALL the dependent Modules will be loaded before running any code.

此代码将不会出现错误,并且可以正常工作:

This code will have no errors, and will work:

localFunc();

import {myFunc1} from 'mymodule';

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

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

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