Status: Work in Progress. Updated: 7 February 2020
Installation
npm install --save-dev @babel/core @babel/cli @babel/preset-env
. Install locally in your project and add it as a dev only dependency.- Add a .babelrc file to the root of your project. This is the Babel configuration file.
{ presets: ['@babel/preset-env'] } or { "presets": [ [ "env", { "targets": { "browsers": ["last 2 versions", "safari >= 7"] } } ] ] }
- Create a “source” directory (and sub-directories) when all source files live (e.g. “src”, “src/js”, “src/css”, etc). In my examples it’s
src
. - Create a “build” directory where all your compiled/transpiled and ready to use files are placed (e.g. “dist”, “build”, “public”). In my examples it’s
dist
.
Running with NPM
- Create an NPM “script” to run it (will have to be run manually. Eg:
"scripts": { "build": "babel src -d dist" },
- Run
npm run build
on the command-line and Babel will transpile all JavaScript under the “src” directory and produce output files in the “dist” directory.
Running with webpack
npm install webpack webpack-cli --save-dev
– Install webpack and the CLI.- Add a “script” to npm’s packages.json:
"scripts": { "build": "webpack --config webpack.config.js" },
- Create a webpack.config.js in the root of the project
const path = require("path"); module.exports = { mode: 'development', entry: "./src/js/index.js", // Note: "src" is the source directory name from above. output: { path: path.resolve(__dirname, "dist"), // Note: "dist" is the build directory name from above. filename: "bundle.js" } };
- Run
npm run build
to build files into the “dist” folder. - Install the Babel loader for
npm install babel-loader babel-core --save-dev
.- NOTE: babel-core is not the same as @babel/core. Use @babel/core now.
- Add the following to your webpack.config.js file:
module.exports = { // ... existing content is here ... module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } } ] } };
- “This uses a regex statement to identify the JavaScript files to be transpiled with the babel-loader, whilst excluding anything in the node_modules folder from that. Lastly, the babel-loader is told to use the babel-preset-env package installed earlier, to establish the transpile parameters set in the .babelrc file.” [src]
- Run
npm run build
again.
Resources
- Setting up an ES6 Project Using Babel and webpack (sitepoint) – An excellent, easy to follow article to get you started.
- How to configure Webpack 4 from scratch for a basic website – Another good, easy to follow tutorial.
- http://ccoenraets.github.io/es6-tutorial-data/babel-webpack/ – Short and to the point.
- https://babeljs.io/ – Official Babel site.
- https://babeljs.io/en/setup – Official guide and examples to using Babel.
Looking into: