简体   繁体   English

JavaScript ES6模块+ Traceur

[英]JavaScript ES6 modules + traceur

I'm using ES6 modules transpiled to ES5 with traceur . 我使用ES6模块 transpiled到ES5与traceur
Transpilation is done via grunt + grunt-traceur 通过grunt + grunt-traceur完成翻译

Traceur allows you to pick which module handler to use: its own, AMD, commonJS or inline. Traceur允许您选择要使用的模块处理程序:它自己的,AMD,commonJS或嵌入式。
I have tried most of them, but none seems to to work. 我已经尝试了大多数,但是似乎都没有用。 Why? 为什么?

TestClass.js TestClass.js

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

Main.js Main.js

import TestClass from './TestClass';

var test = new TestClass();

Gruntfile.js (extract) Gruntfile.js (摘录)

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

index.html (extract) index.html (摘录)

<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) { 未捕获的错误:匿名define()模块不匹配:函数($ __ 0){

It seems that there are issues with the grunt plugin, but even using an older version doesn't seem to help. 似乎grunt插件存在问题 ,但是即使使用旧版本也似乎无济于事。

Code was adapted from an article . 代码改编自一篇文章

It seems that I had very similar problem (and googled your question trying to find solution). 看来我遇到了非常类似的问题 (并在Google搜索您的问题以尝试找到解决方案)。

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. 首先,您需要使用treceur运行时加载这两个js脚本。 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. 请注意,您必须在type属性中将脚本指定为module -s。

Than you have to load init module: 比您必须加载init模块:

<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. 我使用grunt-traceur的0.2.9版本和treceur运行时的0.0.72版本。 Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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