带有Node.js的Typescript baseUrl

Jee*_*ing 8 node.js typescript

为了避免长路径import,我在我的使用中使用了Typescript baseUrl选项tsconfig.json

这是我的tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "none",
        "removeComments": true,
        "rootDir": "./",
        "outDir": "Build",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "pretty": true,
        "baseUrl": "./"
    },
    "exclude": [
        "node_modules",
        "Build"
    ]
}
Run Code Online (Sandbox Code Playgroud)

所以不要这样做

import foo from "../../../../hello/foo"
Run Code Online (Sandbox Code Playgroud)

我这样做

import foo from "hello/foo"
Run Code Online (Sandbox Code Playgroud)

它在Typescript编译器中工作正常,但是当我用node.js运行我的应用程序时,我有这个错误:

module.js:474
    throw err;
    ^

Error: Cannot find module 'hello/foo'
Run Code Online (Sandbox Code Playgroud)

Ps:我不想替换require()我在互联网上看到的功能

所以,我怎样才能使Node.js的用的baseUrl工作或做类似的打字稿更换路径"hello/foo""../../../../hello/foo"

打字稿编译器版本:

Version 2.3.0-dev.20170303
Run Code Online (Sandbox Code Playgroud)

Evg*_*nov 8

NODE_PATH使用node.js运行应用程序时传递env param

例:

set NODE_PATH=./src
node server.js
Run Code Online (Sandbox Code Playgroud)


Lui*_*rez 5

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": "./",
Run Code Online (Sandbox Code Playgroud)

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"
  },
Run Code Online (Sandbox Code Playgroud)