Express & ES6 Boilerplate
Tags: node, express, es6, babel
Published: 2023-06-06 20:02:50

Let's set up an Express.js app using ES6. I will be using the Babel compiler to compile our ES6 code to ES5. Babel is a JavaScript compiler that enables one use next generation JavaScript, today. This Tutorial assumes that you have installed the Node Package Manager(NPM) and the Node.js Engine in your development environment. If you do not have Node.js installed, you can download and install it from the [Node.js website](https://nodejs.org/en). Also, you can download the full codebase [here](https://github.com/itwebtiger/express-amazon-cognito/tree/init-expressjs) if you are interested in this es6 node-express boilerplate.

### Step 1: Set up the project
1. Create a new directory for your project and navigate to it.
2. Initialize a new Node.js project by running the following command in your terminal:

```bash
npm init -y
```

### Step 2: Install dependencies

1. Install Express and other required packages by running the following command:

```bash
npm install express
```

### Step 3: Configure Babel

1. Install Babel and the necessary plugins by running the following command:

```bash
npm install --save-dev @babel/core @babel/preset-env @babel/register
```

2. Create a file named .babelrc in the root directory of your project and add the following content:

```

{
  "presets": ["@babel/preset-env"]
}
```


### Step 4: Create the Express app

1. Create a file named app.js in the root directory of your project.
2. Add the following code to app.js to set up a basic Express application:

```
import express from 'express';

const app = express();

// Define routes and middleware here

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
```

In your terminal, run the following command to start the server:

```bash
node -r @babel/register app.js
```

### Step 5: Install nodemon

1. Install nodemon as a development dependency by running the following command in your project's root directory:

```bash
npm install --save-dev nodemon
```

2. Open your project's package.json file and modify the "scripts" section to include a new script called "start" with the command to run the server using nodemon(`"start": "nodemon --exec babel-node app.js"`). Your package.json file should look like [this](https://github.com/itwebtiger/express-amazon-cognito/blob/init-expressjs/package.json):

```
{
  "name": "express-amazon-cognito",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node app.js",
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "@babel/core": "^7.22.1",
    "@babel/node": "^7.22.1",
    "@babel/preset-env": "^7.22.4",
    "@babel/register": "^7.21.0",
    "nodemon": "^2.0.22"
  }
}
```

3. Save the changes to package.json.

4. Open your terminal and navigate to your project's root directory.

5. Start the server using the following command:

```bash
npm start or yarn start
```

Now, nodemon will automatically monitor your files for changes and restart the server whenever you save changes to your code.

### Step 6: Set up Prettier and ESLint

1. Install the necessary packages as dev dependencies:

```bash
npm install --save-dev prettier eslint eslint-config-prettier eslint-plugin-prettier
```

2. Create an ESLint configuration file by running the following command and following the prompts:

```bash
npx eslint --init
```

This command will guide you through setting up ESLint. Make the following selections when prompted:

    - How would you like to configure ESLint? -> Use a popular style guide
    - Which style guide do you want to follow? -> Airbnb
    - Do you use TypeScript? -> No
    - Where will your code run? -> Node
    - How would you like to define a style for your project? -> Use a configuration file
    - Which format do you want your config file to be in? -> JavaScript

3. Install the necessary Babel ESLint plugin:

```bash
npm install --save-dev babel-eslint
```

4. Open the .eslintrc.js file that was created in your project's root directory.
   Modify the configuration file to extend the plugin:prettier/recommended configuration and set the parser option to babel-eslint. It should look something like this([source file](https://github.com/itwebtiger/express-amazon-cognito/blob/init-expressjs/.eslintrc.js)):

```
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['airbnb-base', 'plugin:prettier/recommended'],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  rules: {
    'prettier/prettier': 'error',
  },
};
```

5. Create a [.prettierrc file](https://github.com/itwebtiger/express-amazon-cognito/blob/init-expressjs/.prettierrc) in your project's root directory and specify your desired Prettier formatting rules.

```
{
  "singleQuote": true,
  "trailingComma": "es5"
}

```

6. Add a Prettier script to your package.json file's "scripts" section:

```
"scripts": {
  "prettier": "prettier --write '**/*.{js,json}'"
}
```

Now you can run ESLint and Prettier on your project. For example, to run ESLint on your entire project, use the following command:

```bash
npx eslint .
```

To format your code with Prettier, run the following command:

```bash
npm run prettier
```

Feel free to adjust the ESLint and Prettier configurations to meet your specific project requirements.

### Step 7: Set up env

1. Install the dotenv package, which allows you to load environment variables from a .env file:

```bash
npm install dotenv
```

2. Create a .env file in your project's root directory. Add the following line to the .env file, specifying the desired port number:

```bash
PORT=3000
```

3. In your main entry file (e.g., app.js or index.js), import the dotenv package using ES6 syntax at the top of the file:

```bash
import dotenv from 'dotenv';
```

4. Load the environment variables from the .env file by invoking the config method on the dotenv object:

```bash
dotenv.config();
```

5. Update the code where you define the port for your Express.js server. Use destructuring to extract the PORT variable from process.env:

```bash
const port = process.env.PORT || 3000;
```

In this example, the PORT variable will hold the value from the .env file. If it is not set, the port variable will default to 3000.

6. Start your Express.js server using the port variable:

```bash
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```

Now your Express.js server will read the port number from the .env file using ES6 syntax.

You can adjust the code and syntax to match your specific project structure and requirements.
You can download the full codebase [here](https://github.com/itwebtiger/express-amazon-cognito/tree/init-expressjs) for this article.

If you like this type of content you can give me a star on my [GitHub repository](https://github.com/itwebtiger/express-amazon-cognito/tree/init-expressjs) for the latest updates.

#### References:
https://chrisw.vercel.app/projects/node/express/getstarted
https://github.com/itwebtiger/express-amazon-cognito/tree/init-expressjs