带有Babel的简单ES7装饰器 [英] Simple ES7 decorator with babel

查看:360
本文介绍了带有Babel的简单ES7装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法运行以下代码: https://www.npmjs.com/package/core-decorators#readonly

I can not run this code: https://www.npmjs.com/package/core-decorators#readonly

我用口香糖和通心粉.我有package.json

I use gulp and babel. I have package.json

{
  "name": "my-first-decorator",
  "version": "0.0.1",
  "dependencies": {
    "core-decorators": "^0.8.1"
  },
  "devDependencies": {
    "babel-plugin-transform-class-properties": "^6.0.14",
    "babel-plugin-transform-decorators": "^6.0.14",
    "babel-preset-es2015": "^6.1.2",
    "babelify": "^7.2.0",
    "browserify": "^12.0.1",
    "gulp": "^3.9.0",
    "vinyl-source-stream": "^1.1.0"
  }
}

我有gulpfile.js

and I have gulpfile.js

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('default', function () {
    return browserify({entries: 'app.js', extensions: ['.js'], debug: true})
        .transform('babelify', {
            presets: ['es2015'],
            plugins: ['transform-class-properties', 'transform-decorators']
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('dist'));
});

我的app.js

import { readonly } from 'core-decorators';

class Meal {
  @readonly
  entree = 'steak';
}

var dinner = new Meal();
dinner.entree = 'salmon';
// Cannot assign to read only property 'entree' of [object Object]

我写到控制台:

$ npm install
$ gulp

我打开浏览器,但控制台为空. 应该有:不能分配为只读[object Object]的属性"entree"

I open my browser, but the console is an empty. There should be: Cannot assign to read only property 'entree' of [object Object]

我的应用编译后:

var _coreDecorators = require('core-decorators');

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Meal = function Meal() {
  _classCallCheck(this, Meal);
};

var dinner = new Meal();
dinner.entree = 'salmon';
// Cannot assign to read only property 'entree' of [object Object]

推荐答案

您需要添加stage-1预设,因为装饰器尚未标准化(因此它们不会也不会包含在es2015预设中).

You need to add the stage-1 preset, since decorators are non-standardised yet (so they are not and will not be included into the es2015 preset).

https://babeljs.io/docs/plugins/preset-stage-1/

这篇关于带有Babel的简单ES7装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆