javascriptnode.jstypescriptnode-modules

How to create a local module in TypeScript


I have created in folder src/modules/my-module/ which has package.json and defined the main file which exports everything we need.

I can import from it now import {A} from '../../modules/my-module'

I want to change the syntax into import {A} from 'my-module' and I have a few reasons for it:

I have managed to compile it by adding to tsconfig.json

"paths": {
  "my-module": ["src/modules/my-module"]
}

But I can't run the result via node.js as the node can't find the module. Is there any way to use non-realtive module reference in such scenario.


Solution

  • TS doesn't convert that "my-module" when transpiling your ts files to js.

    Using module-alias package might solve your problem.

    Add this configuration below into package.json:

    "_moduleAliases": {
       "my-module": "<your_build_folder>/modules/my-module"
    },
    

    And this code on first line of your main file (server.ts/index.ts)

    import 'module-alias/register';