tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "esnext",
"sourceMap": true,
"esModuleInterop": true,
"baseUrl": ".",
"moduleResolution": "node"
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}
package.json
{
"name": "koa-typescript-test",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"start": "ts-node src/index"
},
"dependencies": {
"koa": "^2.5.1",
"ts-node": "^7.0.0",
"typescript": "^2.9.2"
}
}
src/foo/bar.ts
export default bar = 'bar'
src/index.ts
import Koa from 'koa'
import bar from 'src/foo/bar'
...
When I run yarn start, the error occur:
Error: Cannot find module 'src/foo/bar'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
at Function.Module._load (internal/modules/cjs/loader.js:520:25)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/xxx/koa-typescript-test/src/index.ts:2:1)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Module.m._compile (/xxx/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Object.require.extensions.(anonymous function) [as .ts] (/xxx/koa-typescript-test/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:612:32)
error Command failed with exit code 1.
The TypeScript compilation is passed, but the ts-node execution is failed. It seems ts-node can't find module with custom non-relative import.
How can I solve this?
This is still node.js, TypeScript doesn't rewrite your paths even if you tell it that the baseUrl is someplace else. That feature is intended if something else is handling baseUrl management (such as a browser, Webpack, etc). If you really want this, try tsconfig-paths (link in README - https://github.com/TypeStrong/ts-node#loading-tsconfigjson).
Thanks. tsconfig-paths wokrs for me!
Most helpful comment
This is still node.js, TypeScript doesn't rewrite your paths even if you tell it that the
baseUrlis someplace else. That feature is intended if something else is handlingbaseUrlmanagement (such as a browser, Webpack, etc). If you really want this, trytsconfig-paths(link in README - https://github.com/TypeStrong/ts-node#loading-tsconfigjson).