Skip to content

Instantly share code, notes, and snippets.

@umidjons
Last active January 3, 2019 13:14
Show Gist options
  • Save umidjons/fada437f22bfb6e430a18d708c90ca83 to your computer and use it in GitHub Desktop.
Save umidjons/fada437f22bfb6e430a18d708c90ca83 to your computer and use it in GitHub Desktop.
Using decorators. Transpile with Babel. Configure Gulp task.

Using decorators. Transpile with Babel. Configure Gulp task.

Install necessary modules

npm i -D babel-cli babel-plugin-transform-decorators-legacy
npm i -D gulp gulp-sourcemaps gulp-babel

Configure npm run build and npm start commands. Also specify babel options, such as plugins.

package.json file

{
  "name": "t1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node dist/s1.js",
    "build": "gulp"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.16.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "gulp": "^3.9.1",
    "gulp-babel": "^6.1.2",
    "gulp-sourcemaps": "^1.6.0"
  },
  "babel": {
    "plugins": [
      "transform-decorators-legacy"
    ]
  }
}

gulpfile.js file

var gulp = require('gulp');
var babel = require('gulp-babel');
var sourceMaps = require('gulp-sourcemaps');

gulp.task('compile:js', function () {
    return gulp.src('src/**/*.js')
        .pipe(sourceMaps.init())
        .pipe(babel())
        .pipe(sourceMaps.write('.'))
        .pipe(gulp.dest('dist/'));
});

gulp.task('watch:js', function () {
    return gulp.watch('src/**/*.js', ['compile:js']);
});

gulp.task('default', ['compile:js', 'watch:js']);

src/s1.js file

@classLevel('debug')
@instanceLevel('warning')
class Person {
    constructor(name) {
        this.name = name;
    }
}

function classLevel(value) {
    return function decorator(target) {
        target.level = value; // add property to the target class
    }
}

function instanceLevel(value) {
    return function decorator(target) {
        target.prototype.level = value; // add property to the target class instance
    }
}

console.log('Person.level=', Person.level);

let jack = new Person('Jack');
console.log('Jack.level=', jack.level);

Start build task

npm run build

Sample output

> t1@1.0.0 build f:\projs\t1
> gulp

[12:53:01] Using gulpfile f:\projs\t1\gulpfile.js
[12:53:01] Starting 'compile:js'...
[12:53:01] Starting 'watch:js'...
[12:53:01] Finished 'watch:js' after 13 ms
[12:53:01] Finished 'compile:js' after 156 ms
[12:53:01] Starting 'default'...
[12:53:01] Finished 'default' after 31 μs

Execute dist/s1.js

node dist/s1.js

Sample output

Person.level= debug
Jack.level= warning
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment