JeePing
JeePing

Reputation: 489

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

Upvotes: 26

Views: 13193

Answers (4)

Luis Suarez
Luis Suarez

Reputation: 93

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

tsconfig.json

"compilerOptions": {
    // Other options...
    "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"
  },

Upvotes: 9

chxru
chxru

Reputation: 581

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"
 }

Upvotes: 2

Alberto Ruiz
Alberto Ruiz

Reputation: 376

Just add this line inside your tsconfig.json file.

"baseUrl": "./src"

It should work like a charm.

Upvotes: -3

Evgeny Rodionov
Evgeny Rodionov

Reputation: 2643

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

Example:

set NODE_PATH=./src
node server.js

Upvotes: 26

Related Questions