简体   繁体   中英

JavaScript ES6 modules + traceur

I'm using ES6 modules transpiled to ES5 with traceur .
Transpilation is done via grunt + grunt-traceur

Traceur allows you to pick which module handler to use: its own, AMD, commonJS or inline.
I have tried most of them, but none seems to to work. Why?

TestClass.js

export default class TestClass {
    constructor() {
        alert('test');
    }
}

Main.js

import TestClass from './TestClass';

var test = new TestClass();

Gruntfile.js (extract)

traceur: {
    options: {
        experimental: true,
        blockBinding: true,
        modules: 'amd'
    }
}

index.html (extract)

<script src="js/vendor/traceur-runtime.js"></script>
<script src="js/vendor/require.js"></script>

<script defer async src="js/compiled/Main.js"></script>

Error given

Uncaught Error: Mismatched anonymous define() module: function ($__0) {

It seems that there are issues with the grunt plugin, but even using an older version doesn't seem to help.

Code was adapted from an article .

It seems that I had very similar problem (and googled your question trying to find solution).

I had not seen error provided by you, anyway post here my implemetation, maybe it helps you.

First of all you need to load both js script with treceur runtime. Like this:

<script src="js/vendor/traceur-runtime.js"></script>
<script defer async src="js/compiled/TestClass.js" type="module"></script>
<script defer async src="js/compiled/Main.js" type="module"></script>

Note that you must specify that your scripts is module -s in type attribute.

Than you have to load init module:

<script>
    System.get('public_js/init'); 
    // pass your init module name as a parameter
    // you can see it in private __moduleName variable in compiled init.js
</script>

That implemetation works well for mine. I use 0.2.9 version of grunt-traceur and 0.0.72 version of treceur runtime. Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM