In this post, we will look at how to create a basic Babel project using Node in Visual Studio Code. Babel is a useful plugin that transpiles JavaScript to various versions. Let’s look at how to set this up.
First, let’s create a new folder in Windows called babeltest and run npm init -y to create the package:
We now have one file in our directory, the package.json:
Note, alternatively you could have opened VS Code and run the npm init -y from the Terminal:
Let’s open the directory in VS Code:
This opens Visual Studio Code to the folder:
Now let’s create a new file, ES6.js. This will contain some ES6 code, which isn’t supported by browsers such as IE 11. We will create a function that uses arrow notation to display a given input. It also uses let:
If we run this in Chrome, it works:
Now let’s use Babel to transpile this code so it is compatible with IE 11.
First, let’s install Babel Core:
npm install @babel/core –save
Next, in order to run Babel from the command line, we need to install the Babel CLI:
npm install @babel/cli –save
Our package file shows:
Let’s add the line to scripts:
We’re now ready to see if Babel is working. Run the command below:
npm run babel ES6.js — –out-file Transpiled.js
This produces our Transpiled.js file:
However, we can see the file looks the same as the original ES6.js file. This is because we haven’t told Babel which browser to target.
To do this, we will need to install Babel Presets:
npm install @babel/preset-env –save
We can see if we went to the online Babel transpiler and entered IE 11 we would get the output on the right:
Let’s add this configuration. We will create a file called .babelrc and add configuration
Now when we run our command:
npm run babel ES6.js — –out-file Transpiled.js
Our code is transpiled:
And to target IE 11:
Or for not IE 11:
Which will transpile to ES6:
To run with npm run build, we need to add build to our scripts in our package.json:
Now running npm run build will transpile our code.
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL