Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript baseUrl with Node.js

To avoid long paths in import, I'm using Typescript baseUrl option in my tsconfig.json

Here's my tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "none",
        "removeComments": true,
        "rootDir": "./",
        "outDir": "Build",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "pretty": true,
        "baseUrl": "./"
    },
    "exclude": [
        "node_modules",
        "Build"
    ]
}

so instead of doing this

import foo from "../../../../hello/foo"

I do this

import foo from "hello/foo"

It's working fine in the Typescript compiler, but when I run my app with node.js, I have this error:

module.js:474
    throw err;
    ^

Error: Cannot find module 'hello/foo'

P.s: I don't want to replace the require() function like I've seen on the internet

So how can I make node.js working with baseUrl or make typescript replacing paths like "hello/foo" to "../../../../hello/foo" ?

Typescript compiler version:

Version 2.3.0-dev.20170303
like image 864
JeePing Avatar asked Mar 03 '17 15:03

JeePing


3 Answers

Pass NODE_PATH env param when you run app with node.js

Example:

set NODE_PATH=./src
node server.js
like image 101
Evgeny Rodionov Avatar answered Nov 15 '22 20:11

Evgeny Rodionov


As @jez said you need to set the NODEPATH when running the node app. This is configuration may help you:

tsconfig.json

"outDir": "dist",
"baseUrl": "./",

Package.json

"scripts": {
    "build": "tsc",
    "dev": "NODE_PATH=./ ts-node ./src/index.ts",
    "start": "NODE_PATH=./dist node ./dist/index.js",
    "prod": "npm run build && npm run start"
  },
like image 28
Luis Suarez Avatar answered Nov 15 '22 19:11

Luis Suarez


Windows users might want to use cross-env with above mentioned answers.

package.json

"scripts": {
    "dev": "cross-env NODE_PATH=./ ts-node ./src/index.ts"
 }
like image 1
CharukaHS Avatar answered Nov 15 '22 19:11

CharukaHS