NestJS Views Not gettings added to Dist

Viewed 6148

My folder structure is similar to below.

public
views
src
  main.ts
  /users
       users.controller.ts
       /views
         my-view.hbs
  /books
       books.controller.ts
       /views
         my-view.hbs

This is what i use to add the templates and views

 const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
  );
  console.log(join(__dirname, 'public'));

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');
  hbs.registerPartials(join(__dirname, '..', 'views', 'partials'));

My package.json scripts looks like this

"scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/src/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },

My issue is that when i run nest in dev mode it builds the distribution code and it doesn't add the views and the public folder.

3 Answers

I was having the same problem and I've figured out that "assets" should be inside "compilerOptions", did you confirm the same?

I did make it work like this:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "webpack": false,
    "assets": [
      "**/*.hbs"
    ],
    "watchAssets": true
  },
  "generateOptions": {
    "spec": false
  }
}

Check this section in the official documentation.

With assets, nest build will distribute non-TypeScript files, such as .graphql files, images, .html files and other assets as part of your development build step.

Example:

"assets": ["**/*.hbs"]

Add this to your nest-cli.json file located in the root directory.

I was having the exact same issue. The thing is that the function join that you use for setting the path for the folders is literaly joining the strings inside of it. So, in my case, my views and public folders were outside the src folder.

My line was: app.useStaticAssets(join(__dirname, '..', 'public')); I changed it to: app.useStaticAssets(join(__dirname, '..', 'src/public'));

And that solve my problem.

Related