˟

[Web Dev] How to setup a JavaScript project

Apr. 19, 2021

This post shows you how to set up a JavaScript project from scratch, from which you can include a frontend (e.g. React) or a backend (e.g. Express.js).

Setup a JavaScript project with Node

In order to get started with your new project, create the project folder using the command line or you tools of choice, and navigate into it:

mkdir js-project
cd js-project

In the next step, we will initialize the project with npm which comes with two benefits. First, you can install libraries to you project. And second, you can add npm scripts to start, test, or deploy your project. Initialize the npm with command line:

npm init -y

Now, the initialization should create a package.json file which will be filled with your defaults. The content of the file will look like this:

{
  "name": "js-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Next, create a src/ directory for your project’s source code. In this directory, create a src/index.js file as an entry point to your project:

mkdir src
cd src
touch index.js

Test your setup by adding console.log('Hello World!'); to your index.js file and run the command:

node src/index.js

The logging should appear in the command line after the script is executed. As mention above, you can config your package.json file to run scripts for starting, testing, and deploying. You can define the command above as the starting script:

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

Now you can run npm start in the command line and it will work like before without the specifics of the underlying script.

Node.js with nodemon

You are able to start your application by running the npm start script. However, you need to restart manually everytime you modify your source code. You can change this behaviour with nodemon library. Install nodemon

npm install nodemon --save-dev
{
  "main": "index.js",
  "scripts": {
    "start": "nodemone src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
}

The script will be executed again once your source code changes. This will remove the hassle of restarting the project every time.