Skip to content

Instantly share code, notes, and snippets.

@Alexisvt
Created October 14, 2018 22:30
Show Gist options
  • Save Alexisvt/df595a04567ebee1fdfb2ea9baace8a4 to your computer and use it in GitHub Desktop.
Save Alexisvt/df595a04567ebee1fdfb2ea9baace8a4 to your computer and use it in GitHub Desktop.
How to add path aliases to Nest.js

README FIRST

In order to accomplish this we need to install the next package to our project:

> install module-alias --save

Then we need to modify three files, lets go in order:

Main.ts

In that file we need to include at the beggining the next line:

import 'module-alias/register';

Note: Make sure that line is the first line.

tsconfig.json

Now we need to add more configuration into the tsconfig.json file, the next json is an example:

"compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "sourceMap": true,
    "allowJs": true,
    "outDir": "./dist",
    // the next three lines are what we need to include
    "baseUrl": "./src",
    "moduleResolution": "node",
    "paths": {
      "@common/*": ["common/*"],
      "@company/*": ["company/*"],
      "@usuario/*": ["usuario/*"],
      "@services/*": ["services/*"],
      "@utils/*": ["utils/*"],
      "@menu/*": ["menu/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]

The options are: baseUrl, moduleResolution and paths, the last one is the one where We will add our aliases.

Note: Please make sure to use one * and not two.

package.json

This is the last one, now we need to include the next property into it:

[...the other properties...]
"_moduleAliases": {
    "@common": "dist/common",
    "@company": "dist/company",
    "@usuario": "dist/usuario",
    "@services": "dist/services",
    "@utils": "dist/utils",
    "@menu": "dist/menu"
  },
[...the other properties...]

As we can see, I need to replicate in a similar way the aliases that we include into the tsconfig.json file.

For more information:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment