简体   繁体   English

ES6 动态导入()与 AMD 要求()

[英]ES6 dynamic Import() vs AMD require()

What is difference between:有什么区别:

  • dynamic import() in the ES6+ technology and ES6+ 技术中的动态import()

  • require() in the AMD technology (requireJS library)? AMD 技术中的require() (requireJS 库)?

There are a few differences:有一些区别:

require() is synchronous, import() is asynchronous (returns a Promise). require()是同步的, import()是异步的(返回一个 Promise)。

import is a keyword defined in the ECMA spec, require() is just a function defined by some library. import是 ECMA 规范中定义的关键字, require()只是某个库定义的函数。

You can use require() "natively" in NodeJS and not in browsers, and import() is specified for all JavaScript engines.您可以在 NodeJS 中“本地”使用require()而不是在浏览器中,并且import()是为所有 JavaScript 引擎指定的。

Now if you use a building pipeline (eg Webpack), they do actually do different things:现在,如果您使用构建管道(例如 Webpack),它们实际上会做不同的事情:

require() will bundle the required code into one bundle, just as import stuff would, whereas import() dynamically loads the module at runtime, just as require.ensure would ( doc ) require()将所需的代码捆绑到一个包中,就像import stuff一样,而import()在运行时动态加载模块,就像require.ensure一样 ( doc )

There are some differences but import() can be considered as an official implementation of the legacy AMD libraries like require.js .有一些差异,但import()可以被视为旧版AMD 库(require.js import()的官方实现。 Also, it brings a modern approach.此外,它还带来了现代方法。

The self-evident feature of a legacy AMD is that it comes with the module definition besides import expression.老式 AMD 不言而喻的特点是,除了导入表达式之外,它还带有模块定义。 This means you can define a module that can be imported asynchronously anywhere in the project.这意味着您可以定义一个可以在项目中的任何位置异步导入的模块。

If you don't have a transpiler like BABEL to polyfill EcmaScript proposals on your project or if you work on the legacy codebase and need an AMD solution for improving performance, considering to use some AMD libraries instead of dynamic import can be a better choice.如果你没有像transpiler BABEL到填充工具的EcmaScript建议你的项目,或者如果您对遗留代码库工作,需要提高性能的AMD解决方案,考虑使用一些AMD的库而不是动态的进口可能是一个更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM