Installation and Setup

npm install nestjs-mvc-tools
 

Quick Start

This helps you set up the basic configuration for using the MVC pattern in NestJS.

1. Project Initialization

# MVC template and resource setup
npx nestjs-mvc-tools init
 

Creates a resources directory in the project root path and downloads the necessary dependencies for the internal vite development environment.

2. Static File Path Configuration

// main.ts
import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { join } from "path";

import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  // Added
  app.useStaticAssets(join(process.cwd(), "resources", "public"), {
    prefix: "/public",
  });
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
 

3. Registering the NestMvcCoreModule

// app.module.ts
import { Module } from "@nestjs/common";
import { NestMvcCoreModule } from "nestjs-mvc-tools";

@Module({
  imports: [NestMvcCoreModule.forRoot()],
})
export class AppModule {}
 

4. Creating the Controller

// app.controller.ts
import { Controller, Get } from "@nestjs/common";
import { AppService } from "./app.service";
import { NestMvcView, View } from "nestjs-mvc-tools";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  async getHello(@View() view: NestMvcView) {
    const message = this.appService.getHello();
    return view.render("pages/hello_world/index", { message });
  }
}
 

Connected Template Check

// resources/views/pages/hello_world/index.edge @layout.app({ title:
'Helloworld'})
<h1 data-controller="hello" class="text-3xl">{{ message ?? 'hello world' }}</h1>
@end
 

5. Running the Project

# 1. Run the vite development server
cd resources && npm run dev

# 2. Run the nestjs server
npm run start:dev
 

Using the concurrently library, you can configure it as follows:

// package.json
"scripts": {
  "start:resource": "cd resources && npm run dev",
  "start:dev": "concurrently \"nest start --watch\" \"npm run start:resource\"",
}
 

Then, you can run it with just npm run start:dev.