qarthandso qarthandso - 3 months ago 17
Javascript Question

Simple JavaScript ES6 vs require() importing

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
combined 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?

Answer

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 recommendation 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 comment...

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!
   });
}
Comments