DEV Community

Micael Levi L. C.
Micael Levi L. C.

Posted on • Updated on

Enable/disable NestJS devtools integration without changing your code!

Don't know what NestJS Devtools is? check this out: Introduction to NestJS Devtools with Kamil Mysliwiec


What?

You can use the devtools integration without changing anything in your code! Just use the package nestjs-devtools-loader like this:

npm i --save-dev @nestjs/devtools-integration nestjs-devtools-loader
#      ^^^ No need to pollute the production environment

## then:
nest start --watch --exec "node -r nestjs-devtools-loader/register"
## or:
export NODE_OPTIONS="-r nestjs-devtools-loader/register"
nest start --watch
Enter fullscreen mode Exit fullscreen mode

That's all! Now go to https://devtools.nestjs.com (port 8000) as usual :)

Why?

In order to enable the Devtools integration, we need to do the following changes to our source code:

1) Enable the snapshot generation:

// ...
const app = await NestFactory.create(AppModule, {
  snapshot: true,
})
Enter fullscreen mode Exit fullscreen mode

2) Import the DevtoolsModule dynamic module into the root module:

@Module({
  imports: [
    DevtoolsModule.register({
      http: process.env.NODE_ENV !== 'production',
    }),
  ],
  // ...
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

To me, this is too intrusive since most of the time I won't use the devtools. Also, I believe that having snapshot always enabled will affect the bootstrapping time (so we should use process.env.NODE_ENV !== 'production' in there as well).

How?

Instead, we can leveraging on monkey patching and on the --require (or -r) Node's CLI option to perform those changes for us only when we need.

Now I have one npm-script that will start the app with devtools integration enabled thanks to nestjs-devtools-loader package! Note that that package allows us to define the arguments of DevtoolsModule.register() call.

Check out the full code here: https://github.com/micalevisk/nestjs-devtools-loader/blob/main/lib/loader.js#L43

Top comments (0)