Getting Started ExpressJS 2020
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
--hbs
add handlebars engine support.--css sass
addsassMiddleware
change toscss
later on.--git
add .gitignore.
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
# 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
# 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
Replace style.sass to style.scss
Git commit: set SASS to SCSS
git add .
git commit -avm "set SASS to SCSS"
Handlebars
Add Handlebars Partial view configuration
Let’s edit app.js and add lines
var hbs = require('hbs');
hbs.registerPartials(__dirname + '/views/partials');
So it look like
Create .hbs partials views and layout
Partials
Layout
Git commit: Handlebars partials layout
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.
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.
src:resources/scss
dest:public/css
prefix:/css
Fix path layout.hbs
Change /stylesheets/style.css
to /css/style.css
Git
Ignore style.css
Commit "Resources directory for development"
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
git clone -b bootstrap --single-branch git@github.com:HariantoAtWork/bootstrap-express-2020.git
(Optional) Next Step
- socket.io
- vue