Search code examples
typescripttsconfig

How to make the TypeScript path maps useful in the production code?


I've been working on my TypeScript project and wanted to tackle the relative import ../../../ hell problem. I found out that in tsconfig.json I can specify the baseUrl and paths fields so that my ../../../../interface can become simply @interface when I add such a snippet to the tsconfig.json:

    "baseUrl": ".",
    "paths": {
      "@interface" : ["src/interface"],
    },

and that worked great... for a while. I exchanged the long paths in import statements with shorter versions. VSCode was kind enough to understand the path mapping and coding became easier. When I finally wanted to test the app, I compiled the code with tsc command. When I wanted to run it, I got the error:

Error: Cannot find module '@interface'

I inspected the output JavaScript code and saw that the path in the import has not been exchanged by the compiler, as I would expect, but it was just used in the same form as in the .ts file:

const _interface_1 = require("@interface");

I found an issue on TS GitHub from August 2018 asking about the exact same thing. Until now there has not been a satisfying solution to the problem.

My question is: what is the use case for the path mapping in TypeScript as described in the manual? What's the point of using them if they in the end make the production code not runnable?


Solution

  • I also agree with the comment Aviad has put but without judging. If you must do this, then here is a way:

    Add module module-alias to your dependencies. then add mapping to package.json too:

    "_moduleAliases": {
        "@interface": "dist/interface", // note its referencing dist folder
    },
    

    Then in your main ts file. e.g. index.ts, register the module alias using import "module-alias/register";

    Here you can read more about it