javascript – Typescript:如何解析node.js的绝对模块路径?

前端之家收集整理的这篇文章主要介绍了javascript – Typescript:如何解析node.js的绝对模块路径?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我需要基于baseUrl解析模块,因此输出代码可用于node.js

这是我的src / server / index.ts

import express = require('express');
import {port,databaseUri} from 'server/config';

...

这是我的src / server / config / index.ts

export const databaseUri: string = process.env.DATABASE_URI || process.env.MONGODB_URI;
export const port: number = process.env.PORT || 1337;

运行tsc我能够编译没有错误的所有文件,但是输出:dist / server / index.js是

"use strict";
var express = require("express");
var config_1 = require("server/config");

...

结果找不到模块’server / config’如果我试图将它与node dist / sever / index.js一起使用.

为什么服务器/配置路径没有以任何方式解析,因此可以使用已编译的代码或如何解决它.或者我在做什么或者想错的方式?

我的tsc –version是2.1.4

这是我的tsconfig.json:

{
  "compileOnSave": true,"compilerOptions": {
      "baseUrl": "./src","rootDir": "./src","module": "commonjs","target": "es5","typeRoots": ["./src/types",".node_modules/@types"],"outDir": "./dist"
  },"include": [
      "src/**/*"
  ],"exclude": [
      "node_modules","**/*.spec.ts"
  ]
}

注意我不想使用../../../../relative路径.

最佳答案
微软的typescript github上的This post解释了他们的模块解析过程.他们在评论中解释说,你要做的事情是无法完成的.

this feature,along with the rest of the module resolution
capabilities,are only to help the compiler find the module source
given a module name. no changes to the output js code. if you require
“folder2/file1” it will always be emitted this way. you might get
errors if the compiler could not find a folder2/file1.ts,but no
change to the output.
07001

The compiler does not rewrite module names. module names are
considered resource identifiers,and are mapped to the output as they
appear in the source
07002

因此,typescript中发出的JS不会重写您提供给需要的已发现模块的模块路径.如果您在编译后在节点中运行您的应用程序(它看起来像是快递),那么它将使用node module system解决打字稿编译后的模块引用.这意味着它只会尊重模块中的相对路径,然后它将回退到node_modules以查找依赖项.

that is how it is meant to work. the compiler needs the paths to find
the declaration of your module. module names are resource identifiers
and should be emitted as is and not altered.
07004

您已经基本确认了这个问题中的发出输出.

原文链接:https://www.f2er.com/js/429116.html

猜你在找的JavaScript相关文章