1

I have this project structure:

enter image description here

How to configure tsconfig.json for using paths like @app/, @server/.

I try this:

{
    "compilerOptions": {
        "module": "CommonJS",
        "target": "es5",
        "lib": [
            "esnext",
            "dom"
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": false,
        "baseUrl": "..",
        "paths": {
            "@app/*": [
                "app/*"
            ],
            "@server/*": [
                "server/*"
            ]
        }
    },
    "include": [
        "."
    ]
}

Same config works with webpack and ts-loader, but when i run npx ts-node server/index.ts i got error:

npx ts-node server/index.ts 
Error: Cannot find module '@server/a'

server/index.ts :

import a from '@server/a'

console.log('This is index.ts')

a()
pank
  • 803
  • 1
  • 11
  • 16
  • Does this answer your question? [How to use paths in tsconfig.json?](https://stackoverflow.com/questions/43281741/how-to-use-paths-in-tsconfig-json) – about14sheep Jan 08 '22 at 18:41
  • @about14sheep, no i do all like in this solution. This solution https://stackoverflow.com/a/56162649/4482323 works if `tsconfig.json` in project root folder, but dont work if `tsconfig.json` in `server/` folder. – pank Jan 09 '22 at 10:48

1 Answers1

2

Your config works for webpack because you run webpack from the project root. It does not work for server.ts because the path is relative to its directory. Try:

"paths": {
  "@app/*": [
    "../app/*"
  ],
  "@server/*": [
    "../server/*"
  ]
}

If you need to do it for both, you need two different tsconfig.json - one in the root and one in app or server.

Take a look at my project: https://github.com/mmomtchev/rlayers

It uses this feature a lot.

mmomtchev
  • 2,497
  • 1
  • 8
  • 23