Getting started with Babel
Installation
Make sure latest node.js installed and npm updated.
Init package.json:
npm init -yInstall babel:
npm install --save-dev babel-cli babel-preset-envInstall polyfill:
npm install --save babel-polyfillConfigure
Create .babelrc:
{
"presets": ["env"]
}Add entry to scripts section of package.json file:
"babel": "babel src -d dist"Create html and js
Create src folder for source files and dist for transpiled output.
Create file src/index.js written in ES2015:
const greetings = `Hello World!`;
document.body.innerHTML += greetings;Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Babel Sample</title>
</head>
<body>
<script src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
<script src="dist/index.js"></script>
</body>
</html>Run babel
npm run babel
Load webpage
Open index.html and see output
Debug
Open debugger (Ctrl-Shift-I in Chrome) and navigate to source code, inspect output
Adding source maps
Modify entry in scripts section of package.json file to produce source maps:
"babel": "babel src -d dist -s"Watching source files
Modify entry in scripts section of package.json file to watch for changes:
"babel": "babel src -d dist -w"