Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 462
Razor Avatar asked Oct 05 '14 23:10

Razor


1 Answers

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.

like image 65
Glen Swift Avatar answered Oct 06 '22 01:10

Glen Swift