Typescript:如何parsingnode.js的绝对模块path?
我需要基于baseUrl
来parsing模块,所以输出的代码可以用于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
我能够编译所有文件没有erros,但输出: dist/server/index.js
是
"use strict"; var express = require("express"); var config_1 = require("server/config"); ...
导致与如果我试图与node dist/sever/index.js
使用它Cannot find module 'server/config'
。
为什么server/config
path没有以任何方式解决,所以它可能会使用编译代码或如何使其解决它。 或者我在做什么,或者想错了什么?
我的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
path。
这篇文章在微软的typescript github上解释了他们的模块parsing过程。 在评论中他们解释说,你正在做的事情是不能做的。
此function以及其他模块parsingfunction仅用于帮助编译器在给定模块名称的情况下查找模块源。 没有改变输出的JS代码。 如果你需要“folder2 / file1”,它总是以这种方式发射。 如果编译器无法findfolder2 / file1.ts,则可能会出错,但不会改变输出。 https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-206451221
和
编译器不重写模块名称。 模块名称被认为是资源标识符,并被映射到源代码中出现的输出https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-232470330
所以,从typescript发射的JS不会重写你发现require
的发现模块的模块path。 如果在编译之后在node
运行应用程序(它看起来像使用express),那么将在使用打字稿编译后使用节点模块系统来parsing模块引用。 这意味着它只会尊重模块中的相对path,然后会回退到node_modules来查找依赖关系。
这是如何工作。 编译器需要find模块声明的path。 模块名称是资源标识符,应该按原样发出,而不是更改。 https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-255870508
你已经基本证实了你自己在你的问题发出的输出。