NestJS - assets & views folder not being added to dist folder after build
My folder structure is similar to below:
/assets
/img
/fonts
/views
failure.hbs
success.hbs
/src
main.ts
/users
users.controller.ts
NestJS - assets & views folder not being added to dist folder after build
My folder structure is similar to below:
/assets
/img
/fonts
/views
failure.hbs
success.hbs
/src
main.ts
/users
users.controller.ts
You can copy those folders into the dist
folder by adding these lines to your nest-cli.json
file:
"compilerOptions": {
"assets": [
{
"include": "../assets",
"outDir": "dist/public",
"watchAssets": true
},
{
"include": "../views",
"outDir": "dist/views",
"watchAssets": true
}
],
"watchAssets": true
}
Also make sure nest-cli.json
is included while building the app (example: from Dockerfile)
I came to this thread for NestJS + EJS Setup (late to the party) and below is my directory structure.
/views
index.ejs
/src
main.ts
Note: after changing
compilerOptions
in "nest-cli.json" fixed the issue.
"compilerOptions": {
"assets": [
{
"include": "views",
"outDir": "dist",
"watchAssets": true
}
],
"watchAssets": true,
"deleteOutDir": true
}
I added my own build.js
script when running yarn build
:
package.json
:
"build": "nest build && node build.js"
It copies the views and assets folders into the dist build folder.
build.js
:
const fs = require('fs');
const path = require('path');
copyFolderRecursiveSync('views', 'dist');
copyFolderRecursiveSync('assets', 'dist');
function copyFileSync(source, target) {
let targetFile = target;
// If target is a directory, a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
}
function copyFolderRecursiveSync(source, target) {
let files = [];
// Check if folder needs to be created or integrated
const targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
// Copy
if (fs.lstatSync(source).isDirectory()) {
files = fs.readdirSync(source);
files.forEach(function (file) {
const curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
}