Introduction to Babel
Babel is an indispensable tool for every JavaScript developer. It solves the problem of using new JavaScript features that are not available in older browser versions. With Babel, you can transpile your modern JavaScript code into a syntax that is supported by all browsers.
Installing Babel
To install Babel, you need to use npm and install it locally in your project. Run the following command in your terminal:
npm install --save-dev @babel/core @babel/cli
Babel Configuration
By default, Babel does not do anything useful. You need to configure it and add plugins to transpile your code.
To enable the use of arrow functions in all browsers, you can install the @babel/plugin-transform-arrow-functions
package:
npm install --save-dev @babel/plugin-transform-arrow-functions
Then, create a .babelrc
file in the root folder of your application and add the following content:
{
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
Now, when you run babel script.js
, Babel will transpile your code and convert all arrow functions to JavaScript ES5 functions.
Babel Presets
Babel offers presets to simplify configuration. The two most popular presets are env
and react
.
env
preset
The env
preset allows you to specify which environments you want to support and automatically includes all necessary plugins for modern JavaScript features. For example:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}]
]
}
react
preset
The react
preset is useful for developing React apps. It includes plugins such as preset-flow
, syntax-jsx
, transform-react-jsx
, and transform-react-display-name
.
For more information on presets, visit the Babel plugins documentation.
Using Babel with Webpack
To run modern JavaScript in the browser, Babel alone is not enough. You also need to bundle your code. Webpack is a popular tool for this purpose.
To use Babel with Webpack, you need to install the Babel polyfill runtime functionality:
npm install @babel/polyfill @babel/runtime @babel/plugin-transform-runtime
In your webpack.config.js
file, add the following configuration:
entry: [
'babel-polyfill',
// your app scripts should be here
],
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
include: [path.resolve(__dirname, "src")],
exclude: /node_modules/,
query: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
]
}
The presets and plugins information can be kept inside the webpack.config.js
file, eliminating the need for a .babelrc
file.