我正在尝试回答,
什么时候使用import/export,什么时候使用require()/module.exports?但是当我尝试挖掘时,它似乎变得复杂了。
这是我的理解
- require()/module.exports:这是模块系统的 nodejs 实现。这会同步加载模块。
- 在 es6 中,我们可以使用导入/导出。 the docs说
The import statement is used to import bindings which are exported by another module. Imported modules are in strict mode whether you declare them as such or not. The import statement cannot be used in embedded scripts unless such script has a type="module".
问题 1:这通常如何与 babel 或 webpack 或浏览器一起工作?
在探索过程中,我遇到了诸如 CommonJs、requireJs、异步模块定义 (AMD) 之类的东西
问题 2:我更想了解时间轴,因为这些东西是如何在 javascript 中演变的?
最佳答案
How does this work with babel or webpack or browsers in general?
Babel 和 Webpack 遵循 ES 规范并转译 import
/export
声明到一个文件。因为他们也支持 require
语法,他们通常转译 import
对 require()
的陈述电话和 export
对 module exports
的陈述,然后为模块提供自定义加载器。例如,如果您有:
// A.js
export default function() { }
// B.js
import A from "./A";
A();
然后它被转译为以下 require
语法:
//A.js
exports.default = function() {};
//B.js
var A = require("./A").default;
A();
然后可以将其包装成类似的东西:
(function() { // prevent leaking to global scope
// emulated loader:
var modules = {};
function require(name) { return modules[name]; }
function define(name, fn) {
var module = modules[name] = { exports: {} };
fn(module, module.exports, require);
}
// The code:
define("A", function(module, exports, require) {
// A.js
exports.default = function() { };
});
define("B", function(module, exports, require) {
// B.js
var A = require("A").default;
A();
});
})();
how these things evolved in javascript ?
几年前,写JS仅限于浏览器,加载多个js源只能使用多个<script>
标签并使用全局对象来交换功能。那太丑了。
然后 Nodejs 被发明了,他们需要一种更好的方式来使用模块并发明了 require()
规范的编写者认为需要一个本地语法,所以 import
/export
进行了介绍。
Babel 和其他人随后编写了转译器。
关于javascript - 代码拆分如何与导入/导出、babel 和 webpack 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343330/