Post

Getting Started ExpressJS 2020

Harianto van Insulinde

Reviewing back again I made similar posts about bootstrapping ExpressJS and tools and I’m always look into things how to improve and what could be the new best practise. I’m expecting you use Node Version Manager (nvm) for development.

Some improvements are:

  • no more global installations
  • make use of npx command
  • make use of package.json script attribute to store development bin commands, for example gulp.
  • and more.

Generate project

This project is tested from:
Node v14.2.0, NPM v6.14.4

bash
npx express-generator --hbs --css sass --git express-2020

Project Directory: /vue-express-2020/

--hbs add handlebars engine support.
--css sass add sassMiddleware change to scss later on.
--git add .gitignore.

bash
# install dependencies:
cd express-2020 && npm i

# run the app:
DEBUG=express-2020:* npm start

output

Initiate Git

The following commands will run on /vue-express-2020/ as /

For any project you should initiate git. Luckily the engine already give us some config for .gitignore file.

A collection of useful .gitignore templates

bash
# Initiate Git
git init

# add .gitignore and commit
git add .gitignore  
git commit -avm "INIT .gitignore - express-2020"

# add current structure
git add .
git commit -avm "INIT default file structure ExpressJS ~4.16.1 with Handlebars Sass support"

Add Node version

bash
# Save current Node version to .nvmrc
node -v > .nvmrc

# Commit file
git add .nvmrc
git commit -m "Node $(node -v) NPM $(npm -v)"

Always save node/npm version in your project, so you know the project you build on will always work, future Node version might break your app. And also for working in team, it’s important that they use the same version as well, and will prevent some confusion in the future.

Configure: set SASS to SCSS

Enabling SCSS

js
  indentedSyntax: false, // true = .sass and false = .scss

Snippet: /app.js, Set: true to false

Replace style.sass to style.scss

scss
body {
    padding: 50px;
    font: 14px 'Lucida Grande', Helvetica, Arial, sans-serif;
}

a {
    color: #00b7ff;
}

In /public/stylesheets/ Replace: style.sass to style.scss

Git commit: set SASS to SCSS

bash
git add .
git commit -avm "set SASS to SCSS"

Handlebars

Add Handlebars Partial view configuration

Let’s edit app.js and add lines

js
var hbs = require('hbs');
hbs.registerPartials(__dirname + '/views/partials');

So it look like

js
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('hbs');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
hbs.registerPartials(__dirname + '/views/partials');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');


/*
…
etc.
…
*/

Snippet: app.js

Create .hbs partials views and layout

Partials

handlebars
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" />

File: /views/partials/**header.hbs**

handlebars
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

File: /views/partials/**script.hbs**

Layout

handlebars
<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
{{>header}}
  </head>
  <body>
    {{{body}}}
{{>script}}
  </body>
</html>

file: /views/­****layout.hbs****

Git commit: Handlebars partials layout

bash
git add views/partials/. views/layout.hbs
git commit -m "Handlebars partials layout"

Resources directory for development

We want to separate files from development ./resources to production ./public.

In production we want to load for example all-in-one stylesheet style.css, where we have easily maintainable scss in the resources folder.

none
/resources
  /scss
    style.scss
    
/public
  /css
    style.css
    style.css.map

File Structure

Move scss file

Move public/stylesheets/style.scss to resources/scss/style.scss

Configure sassMiddleware middleware

We want to fix paths to make the middleware work again.

js
app.use(
    sassMiddleware({
        src: path.join(__dirname, 'resources', 'scss'),
        dest: path.join(__dirname, 'public', 'css'),
        prefix: '/css',
        indentedSyntax: false, // true = .sass and false = .scss
        sourceMap: true
    })
)

Snippet: app.js

src: resources/scss
dest: public/css
prefix: /css

Fix path layout.hbs

Change /stylesheets/style.css to /css/style.css

handlebars
<!DOCTYPE html>
<html>

<head>
  <title>{{title}}</title>
  <link rel='stylesheet' href='/css/style.css' />
{{>header}}
</head>

<body>
  {{{body}}}
{{>script}}
</body>

</html>

File: views/layout.hbs

Git

Ignore style.css

gitignore
# public
public/css/style.css*

Snippet: .gitignore

Commit "Resources directory for development"

bash
git add .gitignore app.js views/layout.hbs resources/scss/style.scss 
git rm public/stylesheets/style.scss

git commit -m "Resource directory for development"

Sources

Clone single branch

bash
git clone -b bootstrap --single-branch [email protected]:HariantoAtWork/bootstrap-express-2020.git

(Optional) Next Step