Search code examples
moduleecmascript-6systemjs

Import commonJS, AMD, and ES6 modules at runtime with synchronous syntax


I've been writing a lot of ES6 lately, using import {variable} from 'ES6module' syntax, and compiling the code in-browser with traceur-compiler. I started looking at systemjs since it seemed like it might allow me to use the same syntax to import AMD, commonJS, and ES6 modules.

Reading the documentation has started to confuse me though. I see a lot of asynchronous calls like System.import('path/to/module').then(function(variable) { ... }) which I'm not used to for dependency importing.

I've read Practical workflows for ES6 modules, which covers many different workflows, none of which involves importing an ES6 module and an AMD/commonjs module at runtime. I'm thinking something like this:

import {myObject} from 'my/es6/module';
import {_} from 'lib/underscore';

or if not that, than at least:

import {myObject} from 'my/es6/module';
var _ = require('lib/underscore');

Are either of these possible with systemjs?


Solution

  • This use case is exactly what SystemJS is designed for.

    You can write:

    import {myObject} from 'my/es6/module';
    import _ from 'lib/underscore';
    

    The reason is because CommonJS, AMD and Global modules in SystemJS are treated as if they only export a default property, which corresponds to the default import syntax above.