Using Babel
How to use Babel with your tool of choice.
1Choose your tool (try CLI)
Prototyping
In the browserBuild systems
BroccoliBrowserifyBrunchDuoGruntGulpjspmMakeMSBuildRequireJSRollupSprocketsWebpackStartTemplate engines
PugEditors and IDEs
WebStormDebuggers
Node Inspector2Installation
npm install --save-dev @ava/babel
While you can install Babel CLI globally on your machine, it's much better to install it locally project by project.
There are two primary reasons for this.
- Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time.
- It means you do not have an implicit dependency on the environment you are working in. Making your project far more portable and easier to setup.
We can install Babel CLI locally by running:
npm install --save-dev @babel/core @babel/cli
Note: If you do not have a
package.json
, create one before installing. This will ensure proper interaction with thenpx
command.
After that finishes installing, your package.json
file should include:
{
"devDependencies": {
+ "@babel/cli": "^7.0.0",
+ "@babel/core": "^7.0.0"
}
}
npm install -g babel-node-debug
npm install @babel/register
npm install --save-dev broccoli-babel-transpiler
Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side. See setup build systems for more information.
You can use @babel/standalone
as a precompiled version of Babel or run a bundler on Babel yourself. Check the usage section below for how to use it as a script.
You can also use the many online tools to prototype a script:
Online Editors that run Babel for you:
npm install --save-dev babelify @babel/core
npm install --save-dev babel-brunch
npm install babel-connect
Support for Babel in .NET is provided by the ReactJS.NET project. The core library can be installed via NuGet:
Install-Package React.Core
npm install --save-dev duo-babel
ember install ember-cli-babel
npm install --save-dev grunt-babel @babel/core
# Babel 7
npm install --save-dev gulp-babel @babel/core
npm install --save-dev @babel/register @babel/core
babel-jest
is now automatically loaded by Jest and fully integrated. This step is only required if you are using babel-jest
to transform TypeScript files.
npm install --save-dev babel-jest
Select babel
as the transpiler when running jspm init -p
or to switch an existing project into Babel use:
jspm dl-loader --babel
The jspm package management CLI has been deprecated as of June 2020. See jspm repo for more details.
npm install --save-dev karma-babel-preprocessor @babel/core
npm install --save-dev lab-babel
Installed already on most Unix systems. Available from gow on Windows.
npm install metalsmith-babel
As of Meteor 1.2, the ecmascript
package is installed by default for all
new apps.
meteor add ecmascript
npm install --save-dev @babel/register @babel/core
Support for Babel in ASP.NET 4.x is provided by the ReactJS.NET project. Install the MSBuild task via NuGet:
Install-Package React.MSBuild
npm install --save-dev @babel/core
npm install @babel/core @babel/node --save-dev
jstransformer-babel
supports Babel 6 only.
npm install jstransformer-babel
webpacker is the new default javascript compiler for Rails 6. It comes with built-in support for transpiling with babel. To use it in earlier versions of Rails:
# Gemfile
gem 'webpacker'
bundle install
bundle exec rails webpacker:install
npm install --save-dev requirejs-babel @babel/standalone babel-plugin-module-resolver-standalone
npm install --save-dev @rollup/plugin-babel @babel/core
gem install babel-transpiler
npm install --save-dev sails-hook-babel
# Gemfile
gem "sprockets"
gem "sprockets-bumble_d"
bundle install
npm install --save @babel/core @babel/plugin-external-helpers @babel/plugin-transform-modules-umd @babel/preset-env
npm install -D @start/plugin-lib-babel
npm install --save-dev babel-loader @babel/core
npm install --save-dev @babel/cli
3Usage
Enable Babel support either in package.json
or ava.config.*
{
"ava": {
"babel": true
}
}
Note that AVA always adds a few custom Babel plugins when transpiling your plugins see notes.
For more information see the@ava/babel repo.
Instead of running Babel directly from the command line we're going to put our commands in npm scripts which will use our local version.
Simply add a "scripts"
field to your package.json
and put the babel command
inside there as build
.
{
"name": "my-project",
"version": "1.0.0",
+ "scripts": {
+ "build": "babel src -d lib"
+ },
"devDependencies": {
"@babel/cli": "^7.0.0"
}
}
Now from our terminal we can run:
npm run build
This will run Babel the same way as before and the output will be present in
lib
directory, only now we are using a local copy.
Alternatively, you can reference the babel
cli inside of node_modules
.
./node_modules/.bin/babel src -d lib
For full documentation on the Babel CLI see the usage docs.
babel-node-debug path/to/script.js
Or use the alias:
bode-debug path/to/script.js
For more information see the crabdude/babel-node-debug repo.
To include it you will need to require it at the top of the entry point to your application.
require("@babel/register");
If you are using ES6's import
syntax in your application's entry point, you
should instead import at the top of the entry point to ensure it is loaded first:
import "@babel/register";
All subsequent files required by node with the extensions .es6
, .es
, .jsx
and .js
will be transformed by Babel. The polyfill specified in polyfill is also automatically required.
Not suitable for libraries
The require hook automatically hooks itself into all node requires. This will pollute the global scope and introduce conflicts. Because of this it's not suitable for libraries, if however you're writing an application then it's completely fine to use.
Not meant for production use
The require hook is primarily recommended for simple cases.
For full documentation on the Babel require hook see the usage docs.
var babelTranspiler = require("broccoli-babel-transpiler");
var scriptTree = babelTranspiler(inputTree, options);
For more information see the babel/broccoli-babel-transpiler repo.
With @babel/standalone
<div id="output"></div>
<!-- Load Babel -->
<!-- v6 <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>
See docs for full documentation on
@babel/standalone
.
Via CLI
browserify script.js -t babelify --outfile bundle.js
Via Node API
browserify({ debug: true })
.transform(babelify);
Or a more complete example:
var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");
browserify({ debug: true })
.transform(babelify)
.require("./script.js", { entry: true })
.bundle()
.on("error", function (err) { console.log("Error: " + err.message); })
.pipe(fs.createWriteStream("bundle.js"));
Passing options
CLI
browserify -d -e script.js -t [ babelify --comments false ]
Node API
browserify().transform(babelify.configure({
comments: false
}))
package.json
{
"transform": [["babelify", { "comments": false }]]
}
For more information see the babel/babelify repo.
That's it! Set babel options in your brunch config (such as brunch-config.coffee
) except
for filename
and sourceMap
which are handled internally.
plugins:
babel:
whitelist: ["arrowFunctions"]
format:
semicolons: false
For more information see the babel/babel-brunch repo.
var babelMiddleware = require("babel-connect");
app.use(babelMiddleware({
options: {
// options to use when transforming files
},
src: "assets",
dest: "cache"
}));
app.use(connect.static("cache"));
For more information see the babel/babel-connect repo.
var babel = ReactEnvironment.Current.Babel;
// Transpiles a file
// You can instead use `TransformFileWithSourceMap` if you want a source map too.
var result = babel.TransformFile("foo.js");
// Transpiles a piece of code
var result = babel.Transform("class Foo { }");
Via CLI
duo --use duo-babel
Via Node API
Duo(root)
.entry(entry)
.use(babel)
.run(fn);
For more information see the babel/duo-babel repo.
That's it!
For more information see the babel/ember-cli-babel repo.
grunt.initConfig({
babel: {
options: {
sourceMap: true,
presets: ["@babel/preset-env"],
},
dist: {
files: {
"dist/app.js": "src/app.js",
},
},
},
});
grunt.loadNpmTasks('grunt-babel');
grunt.registerTask("default", ["babel"]);
For more information see the babel/grunt-babel repo.
var gulp = require("gulp");
var babel = require("gulp-babel");
gulp.task("default", function () {
return gulp.src("src/app.js")
.pipe(babel({
presets: ["@babel/preset-env"]
}))
.pipe(gulp.dest("dist"));
});
With source maps
Use gulp-sourcemaps like this:
var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");
gulp.task("default", function () {
return gulp.src("src/**/*.js")
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(concat("all.js"))
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("dist"));
});
For more information see the babel/gulp-babel repo.
In your spec/support/jasmine.json
file make the following changes:
{
"helpers": [
"../node_modules/@babel/register/lib/node.js"
]
}
This file is created when you setup a project with the jasmine init
command. Note that the file paths in helpers
option are relative to spec_dir
, not to project root path.
Create a babel.config.json
in your project root:
{
"presets": ["@babel/preset-env"]
}
For more information see the piecioshka/test-jasmine-babel repo.
In your package.json
file make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
}
}
For more information see the babel-jest repo.
Babel will automatically be used when loading any source with import
or export
module syntax.
JSX support is currently disabled by jspm. To re-enable it, add `"blacklist": []` to `babelOptions` in the jspm configuration file.
module.exports = function(config) {
config.set({
files: [
"src/**/*.js",
"test/**/*.js"
],
preprocessors: {
"src/**/*.js": ["babel"],
"test/**/*.js": ["babel"]
},
"babelPreprocessor": {
// options go here
options: {
presets: ["@babel/preset-env"],
sourceMap: "inline"
},
}
});
};
For more information see the babel/karma-babel-preprocessor repo.
SRC = $(wildcard src/*.js)
LIB = $(SRC:src/%.js=lib/%.js)
lib: $(LIB)
lib/%.js: src/%.js babel.config.json
mkdir -p $(@D)
babel $< -o $@
make
CLI
Add the metalsmith-babel
field to your metalsmith.json
.
{
"plugins": {
"metalsmith-babel": {
// babel options
"presets": ["@babel/preset-env"]
}
}
}
API
var Metalsmith = require("metalsmith");
var babel = require("metalsmith-babel");
new Metalsmith("./source")
.use(babel({
/* babel options */
presets: ["@babel/preset-env"]
}))
.build(function(err, files) {
if (err) {
throw err;
}
console.log("Completed.");
});
For more information see the babel/metalsmith-babel repo.
That's it! Any files with a .js
extension will automatically be compiled
with Babel.
For more information see the
ecmascript
README.md.
Mocha 8
In your package.json
file make the following changes:
Create .mocharc.yaml
in your project root:
require:
- '@babel/register'
Some features may require a polyfill:
# Polyfills for builtin methods
npm install --save core-js
# Polyfills for generator function
npm install --save regenerator-runtime
Add import polyfills before @babel/register
.
require:
- 'core-js'
- 'regenerator-runtime'
- '@babel/register'
Create babel.config.json
in your project root:
{
"presets": ["@babel/preset-env"]
}
For more information see the
babel
mocha-examples.
Mocha 3
--compilers
is deprecated as of Mocha v4.0.0. See further explanation and workarounds.
{
"scripts": {
"test": "mocha --compilers js:@babel/register"
}
}
With polyfill:
{
"scripts": {
"test": "mocha --require babel-polyfill --compilers js:@babel/register"
}
}
Import the task in your MSBuild script:
<UsingTask AssemblyFile="packages\React.MSBuild.2.1.0\React.MSBuild.dll" TaskName="TransformBabel" />
Use it:
<TransformBabel SourceDir="$(MSBuildProjectDirectory)" TargetDir="" />
This will transform every .js
and .jsx
file in the directory, and output a .generated.js
file alongside it.
See the guide for more information
require("@babel/core").transform("code", {
presets: ["@babel/preset-env"],
});
For full documentation on the Babel API see the usage docs.
In your package.json
file make the following changes:
{
"scripts": {
"babel-node": "babel-node --presets='@babel/preset-env' --ignore='foo|bar|baz'"
}
}
Then call your script with:
nodemon --exec npm run babel-node -- path/to/script.js
Arguments caveat
Calling nodemon with babel-node may lead to arguments getting parsed incorrectly if you forget to use a double dash. Using npm-scripts helpers prevent this. If you chose to skip using npm-scripts, it can be expressed as:
nodemon --exec babel-node --presets=@babel/preset-env --ignore='foo\|bar\|baz' -- path/to/script.js
Now you can use ES6 in your pug templates as following.
script
:babel
console.log("Hello World !!!");
class Person {
constructor(name) {
this.name = name;
}
sayName(){
console.log(`Hello, my name is ${this.name}`);
}
}
var person = new Person("Apoxx");
person.sayName();
For more information see the jstransformers/jstransformer-babel repo.
That's it!
For more information see the rails/webpacker repo.
Alternatively, if you need babel to transpile javascript that's processed through sprockets, refer to the setup instructions for integrating babel with sprockets.
Add the following paths to your configuration:
paths: {
es6: '...node_modules/requirejs-babel/es6',
babel: '...node_modules/@babel/standalone/babel.min',
'babel-plugin-module-resolver': '...node_modules/babel-plugin-module-resolver-standalone/index'
}
Then reference files via the es6!
plugin name:
define(["es6!your-es6-module"], function (module) {
// ...
});
For more information see the mikach/requirejs-babel repo.
import babel from '@rollup/plugin-babel';
const config = {
input: 'src/index.js',
output: {
dir: 'output',
format: 'esm'
},
plugins: [babel({ babelHelpers: 'bundled' })]
};
export default config;
For more information see the rollup and @rollup/plugin-babel repos.
require 'babel/transpiler'
Babel::Transpiler.transform File.read("foo.es6")
For more information see the babel/ruby-babel-transpiler repo.
That's it!
For more information see the artificialio/sails-hook-babel repo.
# config/application.rb
extend Sprockets::BumbleD::DSL
configure_sprockets_bumble_d do |config|
config.babel_config_version = 1
end
For more information see the rmacklin/sprockets-bumble_d repo.
import sequence from '@start/plugin-sequence'
import find from '@start/plugin-find'
import read from '@start/plugin-read'
import babel from '@start/plugin-lib-babel'
import write from '@start/plugin-write'
const babelConfig = {
// …
babelrc: false,
sourceMap: true,
}
export const task = () =>
sequence(
find('src/**/*.js'),
read,
babel(babelConfig),
write('build/')
)
For more information see the deepsweet/start repo.
Via config
{
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
For more information see the babel/babel-loader repo.
In Preferences - Tools - File watchers, click + button and select Babel file watcher from the list.
Specify the path to Babel executable and click Ok.
By default all files with a .js
extension will be automatically compiled with Babel upon change. The generated ES5 files and source maps will be saved next to original files.
Lastly, in Languages & Frameworks - JavaScript - JavaScript language version, choose ECMAScript 6.
For more information see the post in the WebStorm blog.
4Create babel.config.json
configuration file
Great! You've configured Babel but you haven't made it actually do anything. Create a babel.config.json config in your project root and enable some presets.
To start, you can use the env preset, which enables transforms for ES2015+
npm install @babel/preset-env --save-dev
In order to enable the preset you have to define it in your babel.config.json
file, like this:
{
"presets": ["@babel/preset-env"]
}