Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use babel-polyfill in gulpfile.js

In Babel docs they just say that to include import "babel-polyfill"; so that I can use ES6 generators but after I included that line in my gulpfile.js I still gen an exception : Uncaught ReferenceError: regeneratorRuntime is not defined This is my gulpfile.js

import 'babel-polyfill';

var gulp = require("gulp"),
babel = require("gulp-babel"),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');

gulp.task("babel", function() {
return gulp.src(jsSrc)
    .pipe(concat('Main.js'))
    .pipe(babel())
    .pipe(gulp.dest(jsDest))
    .pipe(rename('Main-min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(jsDest));
});

jsSrc have maines6.js and other .js files. In maines6.js here is my generator:

function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

I don't know how to use this.. can you help me?

like image 878
Altiano Gerung Avatar asked Jan 12 '16 13:01

Altiano Gerung


1 Answers

Since you're just using gulp and not some sort of module bundler(webpack for e.g)

You should follow this guide https://github.com/babel/gulp-babel#runtime

npm install --save-dev babel-plugin-transform-runtime

and then use it like this

.pipe(babel({
        plugins: ['transform-runtime']
    }))

Should do the trick :)

EDIT:

Seems that babel-plugin-transform-runtime add require calls to the transformed file, so I guess you'll need to use a module loader. I would suggest webpack, although there are alternative like browserify and jspm.

You'll need

npm install -g webpack
npm install babel-loader babel-core babel-polyfill babel-preset-es2015 --save-dev

Then you'll need to create a webpack.config.js file. Here's a very primitive setup.

module.exports = {
    context: __dirname + '/app',
    entry: ['babel-polyfill', './entries/index.js'],
    output: {
        path: 'dist',
        filename: '[name].js'
    },
    module: {
        loaders: [
            {
                test: /\.js/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

With the config above the file structure should looke like this

project/
    node_modules/
    app/
        entries/
            main.js
    dist/
        main.js
    webpack.config.js
    package.json

Then just run webpack from your command line. If you want to get the minified version run webpack -p

like image 112
kosman Avatar answered Oct 20 '22 00:10

kosman