Garsallah mohamed
Garsallah mohamed

Reputation: 156

typescript do not replace non-relative paths defined in tsconfig

I am trying to use custom paths to simplify the import of commonly used modules, and I set this config:

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "outDir": "build",
        "allowJs": true,
        "target": "es5",
        "sourceMap": true,
        "baseUrl": ".",
        "paths": {
            "config": ["app/config"]
        }

    },
    "exclude": [
        "node_modules”,
        "build"
    ]
}

I tried to import the config module using "config", but the app failed in requiring the config the file. The require path inside the compiled file is still "config".

// result:
var config = require("config");
// what is should be:
var config = require("../../config");

Even thought the module resolution log show that it has been resolved.

======== Resolving module 'config' from '/abs/path/routes/internal/signin/index.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
'baseUrl' option is set to '/abs/path', using this value to resolve non-relative module name 'config'
'paths' option is specified, looking for a pattern to match module name 'config'.
Module name 'config', matched pattern 'config'.
Trying substitution 'config', candidate module location: 'config'.
Loading module as file / folder, candidate module location '/abs/path/config', target file type 'TypeScript'.
File '/abs/path/config.ts' does not exist.
File '/abs/path/config.tsx' does not exist.
File '/abs/path/config.d.ts' does not exist.
File '/abs/path/config/package.json' does not exist.
File '/abs/path/config/index.ts' exist - use it as a name resolution result.
======== Module name 'config' was successfully resolved to '/abs/path/config/index.ts'. ========

What am I missing to make the path changes after compilation to point to the right module?

Upvotes: 12

Views: 16985

Answers (3)

Alex Nolasco
Alex Nolasco

Reputation: 19456

It's up to the bundling to perform this action, see also tsconfig-replace-paths. It does replace the references.

E.g.

"scripts": {
  "build": "tsc --project tsconfig.json 
            && tsconfig-replace-paths --project tsconfig.json",
}

However, you will still be left with the bundling problem. See, https://github.com/microsoft/TypeScript/issues/26565

Upvotes: 1

Evandro Neder Rosa
Evandro Neder Rosa

Reputation: 31

You can use this code to fix non-relative imports: obs: install tsconfig-paths and ts-node

"scripts": {
"start": "node -r tsconfig-paths/register -r ts-node/register ./dist/app.js",
}

Upvotes: 3

laptou
laptou

Reputation: 6981

Apparently paths was never intended to actually resolve the url to its relative version. You are supposed to do this using a post-processor of some sort. I am using this Babel plugin.

Upvotes: 3

Related Questions