Typescript: How to allow absolute module paths for node.js?

I need the modules to be solved based on baseUrl , so the output code can be used for node.js

this is my src/server/index.ts

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

and this is my 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; 

Running tsc I can compile all files without erros, but the output: dist/server/index.js is

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

As a result, using Cannot find module 'server/config' if I try to use it with node dist/sever/index.js .

Why the server/config path is not resolved in any way, so one could use the compiled code or how to resolve it. Or what am I doing or thinking wrong?

My tsc --version - 2.1.4

This is my 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" ] } 

Note. I do not want to use the ../../../../relative paths.

+5
source share
1 answer

This post on Microsoft typescript github explains the modular resolution process. In the comments, they explain that what you are trying to do cannot be done.

this function, along with the rest of the permission module capabilities, only to help the compiler find the source of the module given the name of the module. no change to js output code. if required, "folder2 / file1" will always be emitted in this way. you may get errors if the compiler could not find the file folder2 / file1.ts, but there is no change to exit. https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-206451221

and

The compiler does not rewrite module names. module names are considered resource identifiers and displayed on the output as they appear in the source https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-232470330

So, the emitted JS from typescript DOES NOT rewrite the module path for detected modules that you pass require . If you run your application in node after compilation (which is similar to express), then it will use the node module system to remove module references after compiling typescript. This means that it will only respect relative paths in your module, and then it will return to node_modules to find the dependencies.

the way it should work. The compiler needs ways to search for the declaration of your module. module names are resource identifiers and should be emitted as is, not changed. https://github.com/Microsoft/TypeScript/issues/5039#issuecomment-255870508

You basically confirmed this in your issue in your question.

+2
source

Source: https://habr.com/ru/post/1261353/


All Articles