admin管理员组文章数量:1323707
I'm getting ready to use ES6 module import/export via babel but came across this confusing statement in this article.
It states:
The power of ES6’s
import
andexport
bined with therequire()
method, gives us the freedom to organize all of the client-side code into modules and at the same time write the code using all the power of the new version of JavaScript.
This makes it sound like ES6's system and require()
serve two different purposes, thereby making this babel/browserify
approach the best one to take. My understanding was that they both do the same things, just a little differently. Could anyone help explain this?
I'm getting ready to use ES6 module import/export via babel but came across this confusing statement in this article.
It states:
The power of ES6’s
import
andexport
bined with therequire()
method, gives us the freedom to organize all of the client-side code into modules and at the same time write the code using all the power of the new version of JavaScript.
This makes it sound like ES6's system and require()
serve two different purposes, thereby making this babel/browserify
approach the best one to take. My understanding was that they both do the same things, just a little differently. Could anyone help explain this?
1 Answer
Reset to default 9This statement is contradictory. If you got into ES6/ES7 you won't want to use CommonJS-style require
, but you'll always want to load modules asynchronously using import
.
In fact, ES6/ES7 have a programmatic way of importing modules: System.import(...)
, but the loader specification is still being discussed...
Until it gets remendation status, there's a polyfill (and more than this...): SystemJS.
I would avoid any other module loading syntax from now, because your code will be perfectly executable in standard Web browsers in some years with few modifications.
OP asked in some ment...
Why will System.import(...) from ES6 be needed for js modules when we have the ES6 import/export module loading capabilities? Aren't they performing the same tasks?
import
statement can be only at the top of a code file. Sometimes you know what files to load based on executing some kind of logic, and import
syntax doesn't support conditionals.
For example, let's say you've an application which requires plugins, and some options have a flag called loadPlugins
which can be true
or false
. Thus, you'll want to load them if the application wants them loaded:
if(options.loadPlugins) {
Promise.all(
options.plugins.map(plugin => System.import(plugin.path))
).then(() => {
// Do stuff when all plugins have been already loaded!
});
}
本文标签: ecmascript 6Simple JavaScript ES6 vs require() importingStack Overflow
版权声明:本文标题:ecmascript 6 - Simple JavaScript ES6 vs require() importing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742130768a2422148.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论