CodeSnacks

How to setup a simple Node.js project with babel 7

July 6, 2019

Prerequisites:

  • have npm installed
  • have Node.js installed

Let’s start with creating a folder where you keep your application.

mkdir my-project
cd my-project

To start off you’ll need an npm project. Running npm init usually asks you a couple of questions regarding your application. To speed things up you can use the -y flag, that answers all of the question with your default setttings.

npm init -y

This created a package.json file, which tells npm

Let’s continue with creating a folder where you’ll keep the source code of your application. That folder is usually named src. It’s good practice to stick to that naming. We will also create the first JavaScript file within this folder. We will name this file index.js. It’s a convention to name the entry for your application index.

mkdir src
cd src
touch index.js

Now let’s fill the index.js file with some content. We’ll just produce some “Hello Node” output by using the console.log statement.

console.log('Hello Node');

To run it switch to your terminal and from the main application folder my-project run the following command:

node src/index.js

This will print the “Hello Node” to your terminal. Well done! But we can do even better! Therefore we will utilize the package.json file, which was created earlier by running npm init. This file contains a scripts section, which currently consists only of a “test” script. Let’s add a start script with the command to run our application.

{
  ...
  "scripts": {
    "start": "node src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}

Now instead of typing node src/index you can run the application by typing npm start. The package.json is among others used to collect all your scripts to run, test, build … your application. You can run all scripts in the package.json by using the npm run command. Just use npm run your_command_name. npm start is a shorthand for npm run start, because this is used quite often. These shorthands exist for build and test, too. So you can always just use npm build and npm test to run these. For all other scripts you’ll need to use the complete npm run ... command.

Automatically restarting your application using Nodemon

Let’s see how the authors describe [nodemon][]: “nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.”

To install it, use

npm i nodemon -D

npm i is the shorthand for npm install. The -D tells npm, that this is a dev (development) dependency. So nodemon will only be present in your development environment in this case.

Now all you need to do is to replace the node

{
  ...
  "main": "index.js",
  "scripts": {
    "start": "nodemon src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  ...
}

nodemon