Let's use Babel and Browserfy to run ES6 code on old unsupported browsers.
WARNING
OUTDATED: Nowdays (2019+) all major browsers support ES6 natively, so you don't need this anymore. Check caniuse (opens new window) for an updated status of ES6 support.
Let's create an example using some of the ES6 features: export
to create libraries, import
to load an external library, class
to define classes.
<!-- index.html -->
<html>
<body>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
// app.js
/** Import a function from an external file. */
import flashMessage from './an-external-file.js';
/** Example of class definition. */
class Test {
constructor(msg) {
alert(msg);
}
}
/** Using the above class. */
let x = new Test('Hello');
/** Using the imported function from our external file. */
flashMessage('World');
// an-external-file.js
export default function(msg) {
alert(msg);
}
npm
is installednpm --version
4.2.0
npm init
npm install babel-cli babel-preset-es2015 browserify babelify --save-dev
browserify app.js -o app-es2016.js -t [ babelify --presets [es2015] ]
Be aware of spaces in the brackets!
[babelify --presets [es2015]]
[ babelify --presets [es2015] ]
<!-- index.html -->
<html>
<body>
<script type="text/javascript" src="app-es2016.js"></script>
</body>
</html>
If you don't want to repeat step 3 manually, for every change, you can use Grunt to automate this process.
Grunt can monitor changes on JS files and automatically transpile them.
To avoid cache issues, you can change the generated file name on each transpilation. Grunt can handle this, and also automatically change the "src" reference in your index.html
.
That's it. You can now develop in ES6+ and still use it on old unsupported browsers.
WARNING
UPDATE: As for 2019, I strongly suggest you to use the create-react-app
tool instead of the following method. The solution below was written on a time that this tool didn't exist.
npm install react react-dom --save
npm install babel-preset-react --save-dev
browserify app.js -o app-es2016.js -t [ babelify --presets [es2015 react] ]
WARNING
This browserfy
command is different than the previous one without ReactJS module.
If you see this error message:
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Then, you have a wrong spacing in the brackets. Spaces are important for the browserfy
command.