Create a nodejs/express application with express-generator

miary.dev
3 min readJun 19, 2019

--

Prerequisite:

  • nodejs

Installation of prerequisites

Nodejs

We Install nodejs. Go to https://nodejs.org/en/ and download the installer.

I took the version “12.4.0 Current”

We’re checking the installation.

node -v
v12.4.0

Express-generator

Express-generator is an all-in-one tool that allows you to quickly create a node-js application using the express library. Thanks to this generator, it will be possible to specify the template (view), the CSS preprocessor, etc.

We want to install express-generator. We open a console and type

npm install express-generator -g

To install express-generator globally. That means that later, if we want to, we can create an application from any file. We check the correct installation of express-generator by displaying the version installed on our machine. To do this, type this:

express - version
4.16.1

Creation of the application

express - view=hbs - css=sass - git

This command, for example, allows you to create an application that asks for:

  • use the hbs template (Handlebars).
  • configure Sass as a css processor.
  • Add a . gitignore file to the project root.

More information about this command and the possibilities offered by the generator tool : https://expressjs.com/en/starter/generator.html

The following dependencies are then installed

with the following command always in the same folder

npm install

Here is the final tree structure after installing dependencies.

The application is launched by typing

DEBUG=nodejs-express:* npm start

We then open the following URL in our browser: http://localhost:3000/

Et voilà !

What if…

1 — We don’t want to run the previous command every time you edit a file?

It’s called livereload. We see how we do that. In the console, we type this to install the nodemon library. — save-dev adds the library in development mode only. This means that the library will not be compiled with the application in prod.

npm install nodemon - save-dev

Add a script-level entry to the package.json file

"startd": "nodemon ./bin/www"

We will test by modifying a file — for example nodejs-express/routes/index.js

We are changing

res.render('index', { title: 'Express'});

in

res.render('index', { title: 'Madatsara'});

We refresh the page and observe the magic.

2 — We want to use scss rather than Sass

In nodejs-express/app.js

Modify the indentedSyntax line

app.use(sassMiddleware({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
indentedSyntax: false, // true = . Sass and false = . scss
sourceMap: true
}));

and add a scss file in nodejs-express/public/stylesheets/style.scss

Sources : https://github.com/rabehasy/nodejs-express/tree/start

Thanks to A.A for the translation of this article.

FR version

--

--

No responses yet