问题
I can not run this code: https://www.npmjs.com/package/core-decorators#readonly
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"
}
}
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'));
});
my 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]
I write to the console:
$ npm install
$ gulp
I open my browser, but the console is an empty. There should be: Cannot assign to read only property 'entree' of [object Object]
My app after compile:
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]
回答1:
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/
回答2:
I installed packages:
$ npm install core-decorators
$ npm install gulp browserify vinyl-source-stream
$ npm install babelify@6.4.0
!!!!! babelify - 6.4.0 seventh version was not able to run
gulpfile:
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'));
});
and last command :)
$ gulp
来源:https://stackoverflow.com/questions/33635511/simple-es7-decorator-with-babel