Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
bennlich Avatar asked Sep 16 '14 21:09

bennlich


People also ask

Can you mix ES6 and CommonJS?

Import statements: use the importing syntax for whatever file type you are importing to. For example, if you are in an ES6 module file and need to bring in a CommonJS file, use the ES6 import syntax.

Can I import CommonJS module?

CommonJS modules cannot import ES Modules. You are not able to import . mjs files from . js files. This is due to the different nature of the two systems.

What is ES6 module syntax?

An ES6 module is a file containing JS code. There's no special module keyword; a module mostly reads just like a script. There are two differences. ES6 modules are automatically strict-mode code, even if you don't write "use strict"; in them. You can use import and export in modules.

What are the main differences between using CommonJS and ES6 module syntax?

While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways: ES6 modules are pre-parsed in order to resolve further imports before code is executed. CommonJS modules load dependencies on demand while executing the code.


1 Answers

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.

like image 87
guybedford Avatar answered Nov 15 '22 12:11

guybedford