javascript - 代码拆分如何与导入/导出、babel 和 webpack 一起使用?

标签 javascript node.js webpack ecmascript-6 babeljs

我正在尝试回答,

什么时候使用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语法,他们通常转译 importrequire() 的陈述电话和 exportmodule 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/

相关文章:

javascript - 将数据从 jQuery.ajax() 传递到 Angular Controller ?

javascript - 在 TypeScript 中解构参数时找不到错误

Webpack 长期缓存

javascript - Eslint 错误导入没有扩展名的 jsx

ecmascript-6 - 使用 webpack 在 babel 中包含导入路径

javascript - 我可以使用 onpopstate 事件的 target.location.href 来更改页面内容吗?

javascript - 使用箭头键 javascript 和/或 jQuery 增加 html anchor

javascript - 如何限制jquery的搜索范围

node.js - 可视化来自 winston (node.js) 的错误日志

node.js - 端口 80 上的 linux systemd 服务