admin管理员组

文章数量:1323530

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 and export bined with the require() 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 and export bined with the require() 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?

Share Improve this question edited Aug 20, 2016 at 13:12 Michał Perłakowski 92.7k30 gold badges163 silver badges187 bronze badges asked Aug 20, 2016 at 13:06 qarthandsoqarthandso 2,1882 gold badges27 silver badges46 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

This 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