Skip to content
Advertisement

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:

  • When I move the module to another folder, I do not want to change all the code calling this module.
  • Later, I would like to have the possibility to move the module to a separate repository as the npm package and reuse it in multiple projects. I do not want to change all calling code later.

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.

Advertisement

Answer

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';
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement