error

In the KOA + TS project, tsConfig was configured to support fast jumps in its IDE, but compiling with tsNode reported errors

The following code

import {add} from '@/lib'

const output = 'Hello World'

console.log(output)

console.log(add(1.2))
Copy the code

Error: Cannot find module ‘@/lib’

To solve

The @ alias defined in tsconfig.json does not matter to TS-Node. So we suspect that TS-Node does not recognize tsconfig.json. Checked once found the stackoverflow.com/questions/5…

Tsconfig. json will not automatically be recognized after ts-Node 7.0.0, so –files will be added to recognize tsconfig.json.

Run ts-node./ SRC /main.ts –files

The result is still an error

Use your real alias

Json is definitely recognized by stackOverflow, so MY guess here is that TS-Node does not support aliases, since the game is actually webpack. I looked it up and sure enough.

Github.com/TypeStrong/… This Issue shows that we just encountered the problem of not being able to use alias. The solution is that we need to install another tsconfig-Paths package.

npm i -D tsconfig-paths

ts-node -r tsconfig-paths/register ./src/main.ts --files
Copy the code

Success at last.

Use vscode’s debugging tools

Reference: www.barretlee.com/blog/2019/0…

Program specifies the entry file

/ / launch. Json configuration
"runtimeExecutable": "/usr/local/bin/nodemon"."runtimeArgs": [
    "--exec"."ts-node"."-r"."tsconfig-paths/register"."--files"]."program": "${workspaceFolder}/src/main.ts".Copy the code

The above configuration is executed

[nodemon] starting `ts-node -r tsconfig-paths/register --files ./src/main.ts`
Copy the code

Args specifies the entry file

/ / launch. Json configuration
"runtimeExecutable": "/usr/local/bin/nodemon"."runtimeArgs": [
    "--exec"."ts-node"."-r"."tsconfig-paths/register"."--files"]."args": ["${workspaceFolder}/src/main.ts"].Copy the code

The above configuration is executed

[nodemon] starting `ts-node -r tsconfig-paths/register --files /Users/xxx/xxx/src/main.ts`
Copy the code

As you can see, the address becomes an absolute path

conclusion

When using TS-Node, add –files to identify your tsconfig.json file

Install the tsconfig-Paths package to use the path alias