Absolute Paths in NestJS

In order to import application components via a relative path in a Node.js application, it might be better to use absolute paths. With absolute paths, you can move your components wherever you want, and you can see exactly what an import is all about on the import path.

To activate this in a TypeScript project, like all NestJS-Application, you need to add a “path” configuration to the tsconfig.json like this:

"paths": {
"@app/*": ["./src/*"]
}

Now, all files under src can be referred to with “@app/…”. But this does only work for typescript. When typescript is compiled to JavaScript for production, this definition is not valid anymore. For the JavaScript part, there is a package called “module-alias” to reference packages via an alias as “@app”. The package must be installed with the package manager in use. With npm: npm install module-alias. Or with yarn: yarn add module-alias. Documentation to “module-alias” can be found here. For the module configuration, there should be an entry “_moduleAliases” inside the package.json of the project. In this configuration, the alias ‘@app’ is mapped to the ‘./dist’ directory. Thus, because in production, the JavaScript-Sources are stored in the ./dist directory.

That’s nearly all. One little thing is left. As mentioned in the documentation, the module should only be activated in JavaScript with the following line:

require('module-alias/register')

But only if the program is running in production. So, in the main.ts add at the very top this code:

if( process.env.IS_PROUCTION) {
  require('module-alias/register')
}

In development, define an Environment-Variable “IS_PROUCTION” that would prevent the require-statement from being executed.

Nach oben scrollen