Why are my required libs not being converted from ES6 to ES5?

By : jhamm
Source: Stackoverflow.com
Question!

I am writing a react app where I require in another lib that is using ES6 syntax. Here is my code using the lib:

var React = require('react');
var Calendar = require('horario-calendar');

var appts = [];

React.render(<Calendar />, document.getElementById('calendar'));

horario-calendar is the third party app and it is full of ES6 syntax. I have a gulp task, that should transpile all the code to ES6. Here is the task:

var browserify = require('browserify');
var reactify = require('reactify');
var source = require('vinyl-source-stream')
var to5 = require('6to5ify');

module.exports = function(gulp, config) {
    gulp.task('browserify', function() {
        browserify(config.app.src, {debug: true})
            .transform(to5)
            .transform(reactify)
            .bundle()
            .pipe(source(config.app.bundleName))
            .pipe(gulp.dest(config.app.bundle));
    });
};

But it is not transpileing by code that is required in. It is only transpileing my code. I still have ES6 style imports all in the horario-calendar. What do I need to do to transpile that code also?

By : jhamm


Answers

I would recommend using webpack instead of Browserify - you'll additionally enjoy the benefits of JSX hot loader. https://github.com/babel/6to5-loader worked flawlessly for me out of the box, though I did replace this:

{ test: /\.js$/, exclude: /node_modules/, loader: '6to5-loader'}

in their examples, to this:

{ test: /\.jsx$/, exclude: /node_modules/, loader: '6to5-loader'}

since I happened to only be using arrow functions in .jsx files, so look out for that.



Ideally this burden would rest with the third-party library, but if that is not an option, you could attempt to utilize global transforms:

If opts.global is true, the transform will operate on ALL files, despite whether they exist up a level in a node_modules/ directory. Use global transforms cautiously and sparingly, since most of the time an ordinary transform will suffice. You can also not configure global transforms in a package.json like you can with ordinary transforms.

Global transforms always run after any ordinary transforms have run.

So replacing .transform(to5) with .transform({ global: true }, to5).

Also, 6to5 (now Babel) has built-in JSX support, so you shouldn't need Reactify.

By : max


This video can help you solving your question :)
By: admin