简体   繁体   中英

How to use paths with ts-node?

I have this project structure:

在此处输入图像描述

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM