So you want to use the new babel 7 with node? Our goal here will be to set up a minimal node application that is able to run locally and has a build command for remote deployment. Lets get started!
There are a couple of differences with the babel you might be familiar with and v7.
- Babels packages are now scoped just like many other large organisations Babel has renamed it’s NPM packages. This means
babel-clifor example has been renamed to
- No messing around with presets anymore. You can just use
@babel/preset-envnow and optionally define your requirements in the config file.
babel-nodehas been moved from the CLI to it’s own package:
Ok so we have the most important things down. You can optionally read more about the changes on babels website but here is what we need to do next:
Setting up the application structure
We’ll keep it as simple as possible:
First you want to run
npm init to create a
package.json file inside the directory and depending on if you are using Git you might want to run
We’ll set up two directories, one to develop in and one to deploy our compiled assets.
For this example we’ll add just a simple file inside the src directory called
We’ll need to add some babel packages to our project with
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node. These respectively take care of babels general working, the usage of babel in the command line, the ability to use the newest JS features and the usage of babel with node.
For easy development we’ll also add the
nodemon package using
npm install --save-dev which reloads node for us automatically when one of our files is changed.
Finally we just need to tell babel to use the
@babel/preset-env package by creating a
.babelrc file in our project root:
Your project structure should now look like this:
Adding scripts to
Now for the final step we’ll add our commands to the
nodemon --exec babel-node src/server.jsas the
startscript. This tells the nodemon package to watch for file changes, reload when it detects them and use babel-node to run the file
src/server.js. We’ll use this while developing locally.
babel src —-out-dir distas the
buildscript. This tells babel to compile the files from the
srcdirectory and place them in the
node dist/server.jsas the
servescript. This enables us to run our compiled code on a server, the reason we are not just using
nodemonfor this is it uses quite a bit more memory than just using
nodeand adds some startup time to the process which is fine for some applications but can be a huge performance hit in others.
package.json should now probably look something like this:
"start": "nodemon --exec babel-node src/server.js",
"build": "babel src --out-dir dist",
"serve": "node dist/server.js"
Happy developing and good luck!
If you have any questions or suggestions I’ll see you in the comments or alternatively you can hit me up via twitter.