NPM and Babel

This tutroial is part of a series of lessons on Node Package Manager.


We'll use the Babel package to transpile (convert) our ES2019 and ES6 source code into 'Classic' JavaScript. The benefit of transpiling your 'modern' JavaScript code into Classic JavaScript is that older browsers, which may not support modern JavaScript, will be able to run your code.

In the previous lesson you should have downloaded and extracted a folder named npm, which is our sample project for this series of tutorials. If you look inside the the src/js/ folder you'll find a few JavaScript files that are using ES6 and ES2019 syntax. In the following steps you'll use NPM to install various Babel packages to transpile this code into Classic JavaScript so that older browsers can run it.

Open the terminal and navigate to the npm folder.

To install the Babel packages enter the following command. Note that by adding the --save-dev option, the packages will be added to the package.json file:

npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/plugin-syntax-class-properties

Now look in the package.json file and see that the Babel tools are included in it Also note that the node_modules folder has been created inside the npm folder. This folder contains all the packages that you install with NPM.

Create a configuration file for Babel (inside the npm folder), name the file babel.config.js It specifies which browsers and version you are targeting. Add the following code to the file (don't worry if the contents of this file is confusing, I had to fumble with it a bit to get things working properly):

module.exports = {
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "browsers": "ie > 4" // Just added this to test if it would actually change anything
                }
            }
        ]
    ],
    "plugins":  ["@babel/plugin-syntax-class-properties"]
}

Now run this command in the terminal to transpile the modern JavaScript code to Classic JavaScript (make sure you run the command from the npm folder):

npx babel src -d dist

The npx program comes installed with NodeJS (just as npm does), and you can use it to run packages from the command line. Here we are running the babel package and telling it to look for .js files in the src folder. The -d dist option specifies that the transpiled .js files should be placed in a folder named dist. If the dist folder does not exist, it will be created.

Now look at the .js files in the newly created dist folder. You should see that the JavaScript code in them is Classic.

NEXT TUTORIAL: NPM, Gulp, and SASS