Bertuz
Bertuz

Reputation: 2576

(How) can I use System.import in babel along with require.js?

I'm playing a little bit with the new ES6 functionalities and Babel. I'm successfully using the modules export/import functionalities by means of require.js (transpiling into AMD), but the experimental module loader doesn't want to work. Here is my code and configurations:

extract of front-app/tst.js

import {tstimp as functocall} from "front-app/tstimp.js";

...

/**
 * LOADING MODULES DYNAMICALLY
 */
System.import('front-app/tst_dyn_mod')
    .then(some_module => {
        console('using the module!');
        some_module.sayHello();
    })
    .catch(error => {
        console.log('error!');
        console.log(error);
    });

My .babelrc looks like this:

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-es2015-modules-amd"]
}

and the scripts I import are these ones, in that order:

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
        <script src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
        <script data-main="front-app/tst" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js"></script>
        <script src="node_modules/es6-module-loader/dist/es6-module-loader.js"></script>
    </head>
    <body></body>
</html>

Unfortunately what I get is the following error by using firefox:

error! tst.js:695:9
Error: a is undefined
    Error loading http://localhost/es6r1/front-app/tst_dyn_mod

what's that a? Am I missing something? Keep in mind my code is transpiled into AMD, but System is supposed to stay there in the transpiled code (and it IS there). The polyfill should do the dirty job, right?

Upvotes: 1

Views: 839

Answers (2)

Thodoris Greasidis
Thodoris Greasidis

Reputation: 557

Just an update on this, https://github.com/thgreasi/babel-plugin-system-import-transformer has support for non string parameters. Just make sure not to use the updated alias package.

Upvotes: 0

Doc Davluz
Doc Davluz

Reputation: 4250

I successfully get the thing working on Babel 6 with a slighlty different config (babel-node cli & thus commonjs) thanks to this plugin: https://www.npmjs.com/package/babel-plugin-system-import (npm install babel-plugin-system-import-transformer). Here's a excerpt of my .babelrc:

…
"plugins": [
  "system-import-transformer",
  {
    "modules": "common"
  }
]
…

Setting amd instead of common like indicated in the documentation should do the trick for you.

Only limitation of this tiny plugin, you should get a plain string module name like System.import("plainString") and not a computed one (nor string concatenation with +, nor new ES6 template literal and neither variable name). It seemds linked to that line of code.

I will try to PR a fix on that limitation if I can.

Upvotes: 0

Related Questions