Home > OS >  How to import a file for different environment with NodeJS?
How to import a file for different environment with NodeJS?

Time:10-31

There are two files under src folder.

  • main.ts
  • tracing.ts

I want to import tracing in the main.ts only on local environment.

main.ts

1 if(process.env.NODE_ENV === 'local') {
2   import './tracing'
3 }
4 import { ConfigService } from '@nestjs/config';
5 import others...

It can't use process.env.NODE_ENV at the beginning of the main file.

If I import it in the middle of the main file with other way, it said the import should at the top of the file.

const config = app.get(ConfigService);
if (config.get('TRACING_ENABLE')) {
  import './tracing'
}

How to import?

CodePudding user response:

Reposting bogdanoff's comment as an answer:

You can use dynamic imports.

if (process.env.NODE_ENV === "local") {
   await import('./tracing.js');
}
  • Related