繁体   English   中英

尝试在es6中使用Class关键字和模块

[英]trying to use the Class keyword and modules in es6

我在一本书中找到了这个代码:

class Animal(){
    constructor(){
        this.legs = 4;
        this.eyes = 2;
        this.say = "Huh?"
     }
     speak(){
         console.log(this.say)
     }
}

以上应该是定义类的正确方法,但我不能在FF或chrome中使用它。 我得到了SyntaxError: class is a reserved identifier

我也在玩模块。 我放

在firstModule.js文件中export let hello = "hello from the first module"

比我说的

import {hello} from "firstModule"
console.log(hello)

在main.js文件中

我把<script type="text/javascript" src="main.js"></script>放在索引文件中,我得到了SyntaxError: modules are not implemented yet

我想我在使用es6语法时遇到了问题,我认为如果使用babeljs我会特别容易

我希望你能在这个babel“try it out” 链接中看到我试图使用类语句,但是我得到了一个错误Unexpected token (1:15)

如何使用es6的东西? 我认为babel应该将es6翻译成es5。 我究竟做错了什么?

我还在html文件中放了<script type="application/javascript;version=1.7">

它应该是class Animal而不是class Animal()
要在浏览器中使用ES6代码之前支持您正在使用的内容,您需要让babel将代码转换为ES5。 例如, 在浏览器中

<script type="text/babel" src="main.js"></script>

要使用模块,您可以使用babel-node尝试它们,或者可以使用webpack打包js文件并将结果加载到浏览器中。

暂无
暂无

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

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