In the past, I utilized Ant build scripts to separate development and production source code. Now, as I'm working on a 100% JavaScript project, I have decided to implement a similar separation using npm.
If you want to deploy minified frontend files (HTML, CSS, and JS) while keeping your development code as it is, you will need to do the following:
1. Instruct express.js to serve files from different directories.
2. Once you do that, move to your parent directory and run the following commands:
npm init -y
npm install --save-dev html-minifier clean-css-cli terser
3. Add the following to your package.json file:
"scripts": {
"build:backend": "npm run purge:backend && npm run minify:backend",
"purge:backend": "rsync -r --delete --exclude='*' backend/public_dev/ backend/public",
"minify:backend": "npm run copy:images && npm run minify:css && npm run minify:html",
"copy:images": "rsync -a --update backend/public_dev/img/* backend/public/img",
"minify:css": "rsync -a --update backend/public_dev/css/*.css backend/public/css --out-format='%n' | xargs -I {} cleancss backend/public/css/{} -o backend/public/css/{}",
"minify:html": "rsync -a --update backend/public_dev/*.html backend/public --out-format='%n' | xargs -I {} html-minifier --collapse-whitespace --remove-comments --remove-optional-tags --remove-redundant-attributes --remove-script-type-attributes --remove-style-link-type-attributes --use-short-doctype --minify-css true --minify-js true backend/public/{} -o backend/public/{}"
},
Now, running npm run build:backend will delete dangling destination files, copy image files, and copy and minimize CSS and HTML files.
npm install --save-dev html-minifier clean-css-cli tersernpm install --save-dev html-minifier clean-css-cli terser