Babel Basics for Beginners
Prerequisite
- Basic knowledge of node
What is Babel?
A JavaScript compiler.
A toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
Specifically, this means that you can use import ...
for modules rather than the node require(...)
.
Installation
npm install --save-dev @babel/cli @babel/core @babel/preset-env
Create .babelrc
with the following
{
"presets": [
["@babel/env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread"
]
}
The plugins adds
class feature as well as the rest
spread operators from ES6.
Integrating with node
Add the following lines to package.json
.
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
}
Now the npm run build
command will compile index.js
and put it in the dist/
directory. Try running and check that the new file exists!
Suppose we setup a basic server on port 4000 that sends a "Hello from the server" response to us whenever we visit the port.
import http from 'http';
const server = http.createServer((req, res) => {
res.end('Hello this is the server on port 4000!');
}).listen(4000);
console.log('Server is up and running');
export default server;
Run npm build
to see what happens! A dist/index.js
is generated with the following:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _http = _interopRequireDefault(require("http"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const server = _http.default.createServer((req, res) => {
res.end('Hello this is the server on port 4000!');
}).listen(4000);
console.log('Server is up and running');
var _default = exports.default = server;