Search code examples
typescriptnode-modulestsconfig

How can I use paths in tsconfig.json?


I was reading about path-mapping in file tsconfig.json, and I wanted to use it to avoid using the following ugly paths:

Enter image description here

The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.

Enter image description here

How can I configure the paths in file tsconfig.json, so instead of:

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

I can use:

import { Something } from "lib/src/[browser/server/universal]/...";

Will something else be required in the Webpack configuration? Or is the tsconfig.json file enough?


Solution

  • This can be set up on your tsconfig.json file, as it is a TypeScript feature.

    You can do like this:

    "compilerOptions": {
            "baseUrl": "src", // This must be specified if "paths" is.
             ...
            "paths": {
                "@app/*": ["app/*"],
                "@config/*": ["app/_config/*"],
                "@environment/*": ["environments/*"],
                "@shared/*": ["app/_shared/*"],
                "@helpers/*": ["helpers/*"]
            },
            ...
    

    Have in mind that the path, where you want to refer to, takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the documentation.

    The character '@' is not mandatory.

    After you set it up on that way, you can easily use it like this:

    import { Yo } from '@config/index';
    

    The only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

    Reference: Module resolution