Typescript 2.0 has added support for having modules in other places than node_modules with the paths property. More info can be found in the documentation.
When running with ts-node this does not work. It just gives me the error that the module cannot be found.
test1.ts
import * as foo from "foo";
console.log(foo.hello);
lib/foo/index.ts:
export const hello = "hello";
Then running
ts-node --compilerOptions '{"baseUrl": "./", "paths": {"foo": ["lib/foo"]}}' test1.ts
Same error with this tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"foo": ["lib/foo"]
}
}
}
Running tsc works
This would be a runtime error. TypeScript does not rewrite the paths for you. Node does not know where to find your paths based on your configuration. Please see the existing issue: https://github.com/TypeStrong/ts-node/issues/138.
For any search-engine travellers reading this,
This can to some extent be worked around by setting the NODE_PATH to your package.json dir, e.g
tsconfig.json
baseUrl: ".",
"paths": {
"*": [
"*"
]
}
package.json
"test": "export NODE_PATH=./ && mocha"
Then imports like these works for ts-node/register runs as well as tools providing resolve paths (babel, webpack)
import * as log from 'src/utils/log'
Guys, this is a very useful workaround with NODE_PATH should be somewhere in README file. I stuck in two hours with baseUrl/paths problem while not found it in closed issues :)
For those interested I did a PR to enable execution of projects with tsconfig paths in #254.
@MrCrimp @mnasyrov I also used the NODE_PATH work-around, but this can now be solved easier with the tsconfig-paths package. Just add it as a dev dependency and use the -r tsconfig-paths/register option of ts-node or mocha and all paths will work automatically without NODE_PATH :-).
@MrCrimp @mnasyrov I also used the NODE_PATH work-around, but this can now be solved easier with the tsconfig-paths package. Just add it as a dev dependency and use the
-r tsconfig-paths/registeroption of ts-node or mocha and all paths will work automatically without NODE_PATH :-).
Thanks for this hint! I guess to make it work through nyc all it takes is:
.nycrc.json
...
"require": [
"ts-node/register",
"tsconfig-paths/register"
],
...
Most helpful comment
For any search-engine travellers reading this,
This can to some extent be worked around by setting the NODE_PATH to your package.json dir, e.g
tsconfig.json
package.json
Then imports like these works for
ts-node/registerruns as well as tools providing resolve paths (babel, webpack)import * as log from 'src/utils/log'