import 与 require 的两个差异
栏目: JavaScript · 发布时间: 7年前
内容简介:Javascript 的模块化开发,除了在 babel / webpack 等工具链下,大多数情况下,CommonJS 的但两个规范实质上并不等同,所以存在着不少的区别,如不能
Javascript 的模块化开发,除了 RequireJS 代表的 AMD 外,目前广泛使用的是 Node.js 代表的 CommonJS 以及 ES6 的 module。
在 babel / webpack 等 工具 链下,大多数情况下,CommonJS 的 require
和 ES6 的 import
效果等同,babel 的 preset 是 ES2015 以及 webpack 都是把 import
转为 require
(webpack 根据 target 再转为 AMD 或 UMP 等格式)。
但两个规范实质上并不等同,所以存在着不少的区别,如不能 import(var)
但能 require(var)
,详细可查看 ES6 模块系统
,此处记录一下两个可能比较直接影响代码书写的差异点。
import 需要在顶层声明使用
这意味着不能使用条件 import 或在块作用域内,查看 下面例子的 babel 结果 。
// import / export must be at the top level
if (true) {
// import 'baz.import';
}
// require can be at any place
if (true) {
require('baz.require');
}
import 会被提升到模块前面
这意味着解析(或 babel / webpack 构建)的时候会把代码做重整,把 import 代码提到最前面,查看 下面例子的 babel 结果 。
console.log('start');
// imports will be hoisted
console.log('import foo.import');
import 'foo.import';
// but require will stay at it's place
console.log('require foo.require');
require('foo.require');
上述代码 babel 后的结果是
require("foo.import");
console.log("start");
// imports will be hoisted
console.log("import foo.import");
// but require will stay at it's place
console.log("require foo.require");
require("foo.require");
这点意味着,如果基于 ES6 的模块 MA,模块内部有直接运行的代码(而不是调用 export
内容后才运行),并且那代码依赖于特定的 global 变量 v
(全局依赖是个不好的实践)。那么在父模块中先声明赋值 global 变量 v
,然后再 import 模块 MA,模块 MA 内的直接运行的代码能获取到 global 变量 v
的预期是无法实现的。
参考
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Chinese Authoritarianism in the Information Age
Routledge / 2018-2-13 / GBP 115.00
This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!