编译的Typescript路径无法解析

时间:2018-09-26 07:22:02

标签: javascript node.js typescript

我具有以下文件夹结构:

/src
   /ts
     /controllers
        controller1.ts
     /routes
        route1.ts
     index.ts

我的tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./src/ts",
    "outDir": "./dist",
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es2015",
    "sourceMap": true,
    "removeComments": false,
    "paths": {
      "*": [
        "*",
        "dist/*",
        "node_modules/*"
      ]
    },
    "types": [
      "node",
      "express"
    ],
    "pretty": false
  },
  "include":[
    "src/ts/**/*.ts",
    "dist/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "coverage"
  ]
}

例如,我的route1.ts的导入为

import controller1 from 'controllers/controller1';

解决的很好。但是,当我编译node_modules/.bin/tsc时,这些文件在dist文件夹中被编译为

const controller1 = require("controllers/controller1");

当我运行服务器时,我得到了

error: uncaughtException: Cannot find module 'controllers/controller1'

如何获取已编译的打字稿路径?

1 个答案:

答案 0 :(得分:0)

TypeScript不会重写导入路径:请参见this declined suggestion。您将必须在运行时使用相对导入路径或将dist目录添加到NODE_PATH环境变量中。