gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:00 26 4
gpt4 key购买 nike

我需要根据 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");

...

如果我尝试将它与 node dist/sever/index.js 一起使用,结果是 Cannot find module 'server/config'

为什么 server/config 路径没有以任何方式解析,所以可以使用编译代码或如何让它解析它。或者我做错了什么或想错了什么?

我的 tsc --version2.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 路径。

最佳答案

This post在微软的 typescript github 上解释了他们的模块解析过程。他们在评论中解释说您无法完成您想要做的事情。

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. https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-206451221

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 https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-232470330

因此,从 typescript 发出的 JS 不会重写您提供给 require 的已发现模块的模块路径。如果您在编译后在 node 中运行您的应用程序(看起来您使用的是 express),那么它将使用 node module system在 typescript 编译后解析模块引用。这意味着它只会尊重模块中的相对路径,然后会回退到 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. https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-255870508

您基本上已经在问题的输出中亲自确认了这一点。

关于javascript - Typescript:如何解析 node.js 的绝对模块路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41171944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com