Well, no, as thanks to the tools called transpilers you don’t have to worry anymore and just have to write codes freely. A transpiler is a tool which takes source code as input and produces new source code as output, with different syntax that is close or equal to the original code.
Babel can be installed in plenty of different ways according to the project requirements. But, in this post, we will teach you how to install Babel in CLI. To install Babel in the particular system or framework, you have to get the specific guide. As this is a beginner’s guide that’s why we are going to take the CLI system. The step by step guide to install Babel is:
- First, you have to install the package using npm and add it as a dev dependency. Here we are assuming that your Node.js environment is already working properly.
- Now babel-test directory will be created and changed into the directory, then initialize npm and install babel-cli as a dev dependency.
- Next, open package.json and add build command to npm script.
- This command will take the source files from the src directory and output the result in a dist directory.
Note: Before running your Babel, make sure to install plugins that will support all your Babel operations. For the quick action download the Env preset, as this tool will automatically download required plugins according to your targeted browsers.
Now, as you have ready to install Babel system, so you can easily run the Babel using build command. This will take you to the src/main.js, transform it to ES5 code and output the transformed code to dist/main.js. The program will look like:
var a = 1;
var b = 2;
var _ref = [b, a];
a = _ref;
b = _ref;
As you in the above-mentioned example that let has been replaced with the var and Babel has introduced a temporary variable to swap. And that’s the whole purpose of Babel. The code you have written in the src directory will be automatically converted to the older browser codes. By default, if you don’t add any preset, then the transformed code will be automatically generated.
As we have earlier mentioned that Babel won’t do anything on its own. It requires the help of plugins or presets to behave according to the project. Some examples of ES2015 include:
- arrow functions
- block-scoped functions
- template literals
But, sometimes we don’t have time and energy to load each plugin separately. Then, in that case, you can download some pre facilitated presets that will make the processing whole a lot easier. Currently, only three pre facilitated presets are available in the market:
Env – This is the most frequently used preset. This tool will enable you to automatically loads all the necessary transformations to make your code compatible depending on the targeted browsers.
React – This preset transfers typically found React projects, mainly adding compatibility with Flow annotations and JSX.
Flow – And, the Flow preset is used to clean all the Flow annotations.