Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
Garsallah mohamed Avatar asked Apr 10 '17 13:04

Garsallah mohamed


2 Answers

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",
}
like image 40
Evandro Neder Rosa Avatar answered Sep 30 '22 00:09

Evandro Neder Rosa


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.

like image 111
laptou Avatar answered Sep 29 '22 23:09

laptou