ReactJS | Basics of ES, Babel and npm
What is ES?
ES is an abbreviation used for ECMA Script. It is a standard for different scripting languages such as JS (JavaScript) made by ECMA.
ECMA is an abbreviation used for European Computer Manufacturers Association. It is a standards organization based out of Switzerland which takes care of ES. ES10 (2019) is updated in June and its nomenclature is like that the year in which the update is released then the name will be a year plus one such as ES9 (2018).
What is Babel?
github.com/babel
It is a term in which you will listen many times but will find difficult to understand. I will tell you only the overview of this because manually you will not indulge in Babel but automatically things will take place by Babel.
Babel is a free and open-source JavaScript Transcompiler which is mainly used to convert ES6 (2015) and above code into a backward compatible code that can be run by older JS engines. Babel deploys a technique called Polyfill which basically means to fill many areas.
What is npm?
npm is an abbreviation used for node package manager. It a package manager for JavaScript. It is the default package manager that comes with NodeJS when you install it. It consists of a command-line interface and an online database of public packages and private packages that are paid which is called the npm Registry.
ReactJS | Introduction to Babel
Introduction to Babel
Babel is a very famous transpiler which basically allows us to use the future javascript in today’s browsers. In simple words, it can convert the latest version of javascript code into the one that the browser understands. The latest standard version which javascript follows is ES2017 which is not fully supported by all the browsers and hence we make use of a tool such as ‘babel’ so that we can convert it into the code that today’s browser understands.
What is transpiler?
It is a tool which is used to convert source code into another source code which is of the same level. That is why it is also known as a source-to-source compiler. Both the codes are equivalent in nature, considering the fact that one works with the specific version of the browser and one doesn’t.
Note: It is also good to note that a compiler is totally different from a transpiler as the transpiler convert source code into another source code at the same abstraction level, whereas the compiler converts code into a lower level code generally. Like in Java, the source code is converted to byteCode which is lower level and not equivalent.
Why do we need Babel?
The main reason we need babel is that it gives us the privilege to make use of the latest things javascript has to offer without worrying about whether it will work in the browser or not.
Simple Example
Before installing and making use of all the features of the Babel tool, let’s see a simple code of the latest standard version of ES2017 and see what happens to it when we pass it into babel engine.
// sample new version javascript code
const fun = (x) => {x*2};
const a = () => {};
const b = (x) => x;
[1, 2, 3].map((n)=> n+1);
Some of the above code is not supported in some browers, so after transpiling through Babel we will get:
// after transpiling
"use strict";
var fun = function fun(x) {
x * 2;
};
var a = function a() {};
var b = function b(x) {
return x;
};
[1, 2, 3].map(function (n) {
return n + 1;
});
Example :
var webpack = require('webpack')
var path = require('path')
var config = {
entry: './script.js',
modde: 'development',
output: {
path: path.resolve('./'),
filename: 'bundle.js'
}
}
function onComplete (error, stats){
if(error){
console.error(error)
} else {
console.log(stats.toString())
}
}
webpack(config, onComplete)
ReactJS | Using Babel
Now we know that what Babel is, we will focus on how to install it on your machine using node. Babel can be installed easily after following these simple steps.
Requirements :
1.A code editor like atom, sublime text or Visual studio code.
2. Node should be installed on the machine with npm too.
We will install Babel using Node. Open your text editor, then create your directories structure like the one below:
|--node_modules
|--src
--app.js
|--.babelrc
|--package.json
|--package.lock.json
If you know how node works then you know about node_modules, package.json, and package.lock.json. These are automatically formed once we run some commands.
Now, open the command line and set the path to the directory of the folder then write these lines in the cmd:
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
npm install nodemon --save-dev
The first npm commands will install babel dependencies and the second will is used to install nodemon which allows us to update the browser content without refreshing it.
After entering the command we will get:
As we can see in the above image, the command that we used to install babel dependencies are now visible in our ‘package.json’ file.
It is also important to ass the below line inside the .babelrc file which we have in our project directory.
// .babelrc
{
"presets": ["@babel/preset-env"]
}
Now we finally need to add scripts into our ‘package.json’ file.
"start": "nodemon --exec babel-node src/app.js" // inside your scripts tag
The final ‘package.json’ will look like this:
Now we are all set we just need to write normal ES6, 7, 8 code in our app.js file and run it with ‘npx babel filename’ command where ‘filename’ is replaced by app.js here, and we will get the ES5 output in the console.
Example:
// next generation javascript code
let alice = () => {};
let bob = (b) => b;
const usingMap = [1, 2, 3].map((number) => number * 2);
console.log(usingMap); // [2, 4, 6]
var immukul = {
_name: "Mukul",
_friends: ["Mukul", "Mayank"],
printFriends(){
this._friends.forEach(
f =>console.log(this._name + " knows " + f));
}
};
console.log(bob.printFriends());
OUTPUT
2. Example Node Server w/ Babel
Getting Started
First we’ll install @babel/cli, @babel/core and @babel/preset-env.
$ npm install --save-dev @babel/cli @babel/core @babel/preset-env
Then we’ll create a .babelrc file for configuring babel.
$ touch .babelrc
This will host any options we might want to configure babel with.
{
"presets": ["@babel/preset-env"]
}
Then create our server in index.js.
$ touch index.js
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
export default server;
With recent changes to babel, you will need to transpile your ES6 before node can run it.
So, we’ll add our first script, build, in package.json.
"scripts": {
+ "build": "babel index.js -d dist"
}
Then we’ll add our start script in package.json.
"scripts": {
"build": "babel index.js -d dist",
+ "start": "npm run build && node dist/index.js"
}
Now let’s start our server.
$ npm start
You should now be able to visit http://127.0.0.1:1337 and see Hello World.
Watching file changes with nodemon
We can improve our npm start script with nodemon.
$ npm install --save-dev nodemon
Then we can update our npm start script.
"scripts": {
"build": "babel index.js -d dist",
- "start": "npm run build && node dist/index.js"
+ "start": "npm run build && nodemon dist/index.js"
}
Then we’ll restart our server.
$ npm start
You should now be able to make changes to index.js and our server should be restarted automatically by nodemon.
Go ahead and replace Hello World with Hello {{YOUR_NAME_HERE}} while our server is running.
If you visit http://127.0.0.1:1337 you should see our server greeting you.
Getting ready for production use
First let’s move our server index.js file to lib/index.js.
$ mkdir lib
$ mv index.js lib/index.js
And update our npm start script to reflect the location change.
"scripts": {
- "build": "babel index.js -d dist",
+ "build": "babel lib -d dist",
"start": "npm run build && nodemon dist/index.js"
}
Next let’s add a new task: npm run serve.
"scripts": {
"build": "babel lib -d dist",
"start": "npm run build && nodemon dist/index.js",
+ "serve": "node dist/index.js"
}
Now we can use npm run build for precompiling our assets, and npm run serve for starting our server in production.
$ npm run build
$ npm run serve
This means we can quickly restart our server without waiting for babel to recompile our files.
Oh, let’s not forget to add dist to our .gitignore file:
$ touch .gitignore
dist
This will make sure we don’t accidentally commit our built files to git.
Testing the server
Finally let’s make sure our server is well tested.
Let’s install mocha.
$ npm install --save-dev mocha
And create our test in test/index.js.
$ mkdir test
$ touch test/index.js
import http from 'http';
import assert from 'assert';
import server from '../lib/index.js';
describe('Example Node Server', () => {
it('should return 200', done => {
http.get('http://127.0.0.1:1337', res => {
assert.equal(200, res.statusCode);
server.close();
done();
});
});
});
Next, install @babel/register for the require hook.
$ npm install --save-dev @babel/register
Then we can add an npm test script.
"scripts": {
"start": "nodemon lib/index.js --exec babel-node",
"build": "babel lib -d dist",
"serve": "node dist/index.js",
+ "test": "mocha --require @babel/register"
}
Now let’s run our tests.
$ npm test
You should see the following:
Server running at http://127.0.0.1:1337/
Example Node Server
✓ should return 200
1 passing (43ms)
That’s it!
1. package.json
{
"name": "Server01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.12.8",
"@babel/core": "^7.12.9",
"@babel/preset-env": "^7.12.7"
}
}
2.babelrc
{
"presets": ["@babel/preset-env"]
}
3. index.js
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(4000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:4000/');
export default server;
3. Node Import – Babel
1. package.json
{
"name": "babelTest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon --exec babel-node app.js"
},
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.4"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.0",
"babel-preset-stage-3": "^6.24.1",
"nodemon": "^1.11.0"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2. .bablerc
{
"presets": ["env", "stage-3"]
}
3.app.js
import express from 'express';
const PORT = 3000;
var app = express();
app.listen(PORT, ()=> { console.log("Server Connected") });
Reference
ReactJS | Using Babel
ReactJS | Basics of ES, Babel and npm
ReactJS | Introduction to Babel
babel/node
example-node-server
Babel JS – Beginner To Intermediate
CodeLit