Babel
Babel is a highly configurable compiler that lets us use newer JavaScript syntax, transforming the newer JavaScript syntax into older syntax that's supported on a wider range of platforms. Babel supports many other kinds of code transformation plugins, e.g. plugins that "polyfill" missing APIs on platforms that don't support them.
Babel enables debugging of the original source code by including source maps with the compiled JavaScript. JavaScript interpreters will run the compiled code, but map it to the source code in the debugger so that we can debug the source code instead of the (generally quite ugly) compiled output.
If you're looking for a simple React setup, you don't need to install Webpack. You should instead use
create-react-app
, described in the Quick Start section. Manually installing and configuring Babel gives you more control over your stack, but isn't necessary to get started with React.
Plugins and presets
Babel comes in two parts: the core, and plugins. Each individual language feature that Babel can transform, such as ES2015 classes, has a separate plugin. Collections of plugins are grouped into presets, so that we don't have to install and configure hundreds of individual dependencies.
Which presets should we use?
We'll almost certainly want the env
preset, which includes plugins for compiling newer JavaScript syntax into older JavaScript syntax. This plugin is highly configurable, letting us choose which browser versions we want to support.
You'll also need the react
preset to use the React JSX language extension.
With Webpack
To use Babel in a project bundled with Webpack, we should use babel-loader. You can install the necessary dependencies with
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
We can then add the babel-loader
into our webpack.config.js
.
We add a module
section if we don't have one already, specifying a new rule for loading .js
(and potentially .jsx
) files. We configure webpack to load all .js
files with the babel-loader
, so that files are transformed into browser-safe JavaScript. We exclude files in node_modules
, since the libraries we install here should already be compiled by the library authors, and because Babel can get slow when watching too many files at once. We specify the cacheDirectory
option to improve performance by caching compiled files.
Babel Configuration
We can configure Babel by including a .babelrc
file in the root directory of our project. Here we can specify which presets and plugins to use.
Given the presets we downloaded above, create a .babelrc
file and add the following:
Note that we want to use the env
preset with the modules
option set to false
, since Webpack can better optimize our code this way.