Babel ?!
Recently, Javascript has been improved a lot. Especially, the announcement of ES6 has brought huge changes. But, when we use ES6, Node itself is not enough. If you want to use upper version than ES6, we should use Babel which is a tool to transcompile upper verion than ES6 to ES5.
Babel consists of some kinds of small modules.
How To Use Babel
At first, we make a project folder for studying babel, and initialize npm
$ mkdir babel_project && cd babel_project
$ npm init
Install
$ npm install babel-cli -g
$ npm install babel-preset-es2015 –save-dev
After setting the project, we make codes for testing.
Structure
+- babel_project
| - node_modules(for npm modules)
| - dist(folder for build files)
| - src(folder for source codes for testing)
…| +- main.js
…| +- ijunc.js
| package.json
| .babelrc
Using babel as a tool to transcompile to ES5 needs a file which is ‘.babelrc’.
{
"presets": [
"es2015"
]
}
src/main.js
src/ijunc.js
When you want to build and to opearte the file, you can use like below that.
$ node {file you want to build}
But, ‘import’ and ‘export’ are grammars for upper version than ES6. Error is going to happen. you can run the following commands from the terminal:
$ babel src -d dist
=> babel {source file, or folder which files gather in} -d (or -o) {destination folder or output file.js}
-d :: the option passed to Babel for compiling a file. We can also use –out-dir for compiling all files in a directory. The short versions of the options are -o for –out-file and -d for –output-dir
-o :: If you would like to output to a file, you may use –out-file or -o
Let’s run code.
$ node dist/main.js
Like this, Babel has a role as transcompiling ES6 to ES5. Babel is a important tool because React is written by ES6’s grammar such as ‘class’. So, if you have some knowledge about Babel & Webpack, you could have better advantages.
We are going to talk about Webpack next time.