Set up compilation of source code using babel with npm scripts

Trevor Miller
InstructorTrevor Miller

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

We can write our package using the latest JavaScript syntax with a compilation step. In this lesson we will install babel-cli and babel-preset-latest and wire up a build script to compile our code using the babel “latest” preset when source files change. This means those using our package can use it in any version of JavaScript even though we are using the latest syntax for our source code.

[00:04] Let's run npm install babel-cli and babel-preset-latest. These are development dependencies, let's use the save-dev flag to store them in our package.json.

[00:13] Now, if we take a look at our package.json, we see in the dev dependencies that there is the babel-cli and babel-preset-latest. This means that our project has access to the binaries of these packages that we can use in our project. To use them, let's go back up to our scripts and we can add a new script called build.

[00:35] When we run this script, we want it to use our babel binary that we have access to, and compile everything in the source directory out to the build directory.

[00:48] Now, let's add a new configuration to our package.json called babel, and it's going to need a key called presets. This key will take an array, and for us, we just need the latest preset that we've installed.

[01:04] To review, we've installed these development dependencies of the babel-cli and the babel-latest-preset, which gives us access to the latest JavaScript syntax and then inside of our scripts, we've created a build script that's going to compile the source directory to the build directory, and then, we've configured our compiler to use the latest preset that we've installed. Now, we just need to create a source directory, and we should be able to run this build.

[01:33] I'm going to create a directory called source, and then inside of that, create a file called index.js, now inside this file, let's export a default function, this is going to return a string that says, "Hello, World."

[01:48] Now, if we save this file and run our script that we've defined in the package.json by saying npm run build, it says that its output source index into build index, now, we can take a look at our build folder and see that there is an index.js in here that's using backwards compatible JavaScript.

[02:08] If we go back to our package.json and take a look at the main file, we can see that it's referencing this build index.js instead of the source one. This is important so that anyone using npm can consume our package regardless of the type of JavaScript they're using.

~ 5 years ago

FYI preset-latest has been deprecated, use env instead.