Babel is a JavaScript-to-JavaScript transpiler in charge of converting next-level JavaScript or future JavaScript to a version of JavaScript that runs standard on your platform, whether it’s a browser or Node.js. This book introduced a few proposals that are still in their beginning stages. For this new syntax to work, we first have to use Babel to convert it to standard JavaScript for the version running inside the Docker container (Node.js 14). You can also transpile to your own platform versions. The bigger the gap between the standard that the code follows (such as ECMAScript 2020) and the standard supported by your browser or server, the more work Babel must do to transpile the code.
To configure Babel in your project, you must install the necessary dependencies. This book uses Babel 7. Here’s a slice of the project’s package.json:
"devDependencies": {
"@babel/cli": "^7.10.1",
"@babel/core": "^7.10.2",
"@babel/node": "^7.10.1",
"@babel/plugin-proposal-class-properties": "^7.10.1",
"@babel/plugin-proposal-function-bind": "^7.10.1",
"@babel/plugin-proposal-numeric-separator": "^7.10.1",
"@babel/plugin-proposal-pipeline-operator": "^7.10.1",
"@babel/plugin-proposal-throw-expressions": "^7.10.1",
"@babel/preset-env": "^7.10.2",
"@babel/preset-flow": "^7.10.1",
"@babel/register": "^7.10.1",
}
After you install the necessary dependencies, the easiest way to configure Babel is through a .babelrc file at project level:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false,
"targets": {
"node": "current"
},
"debug": true
}
]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-function-bind",
"@babel/plugin-proposal-throw-expressions",
["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }]
],
"sourceMaps": "both",
"comments": true,
"highlightCode": true
}
When Babel is configured, you can run it by using babel-cli. To transpile all files into a dist directory, for example, you can run
babel src --out-dir dist --keep-file-extension --copy-files