3

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

我使用 gulp 和 babel。我有 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

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]的只读属性'entre'

编译后我的应用程序:

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]
4

2 回答 2

2

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

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

于 2015-11-11T05:25:48.070 回答
0

我安装了软件包:

$ npm install core-decorators
$ npm install gulp browserify vinyl-source-stream
$ npm install babelify@6.4.0

!!!!!!babelify - 6.4.0 第七版无法运行

吞咽文件:

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

gulp.task('default', function () {
    return browserify({entries: 'app.js', extensions: ['.js'], debug: true})
        .transform(babelify, {
            stage: 0
        })
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('app'));
});

最后一个命令:)

$ gulp
于 2015-11-22T17:48:40.017 回答