Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

baseUrl of tsconfig.json does not work

my project structure is src/ client/ modules/ server/ app.ts


src/
  client/
  modules/
    DB/
  server/
    app.ts
tsconfig.json

i import a module using non-relative import in app.ts file

import * as DB from '@modules/DB';

because i do not want using from "../modules/DB"

and my tsconfig.json is

{
"compileOnSave": true,
"compilerOptions": {
    "module": "commonjs",
    "target": "ES6",
    "noImplicitAny": true,
    "sourceMap": true,
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "traceResolution": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "typeRoots": [
        "/"
    ],
    "baseUrl": "./src",
    "paths": {
        "@modules/*": [
            "modules/*"
        ]
    }
},
"exclude": [
    "src/client/"
]

}

when i trace the resolution, got this

======== Module name '@modules/DB' was successfully resolved to '/Users/pengju/projects/pomelo-ts-starter/src/modules/DB/index.ts'. ========

it seems to successfuly import

but when compiled, vscode still got wrong with

[ts] Cannot find module '@modules/DB'. 

at import * as DB from '@modules/DB'; in app.ts

then i check compiled app.js, find const DB = require("@modules/DB");

the baseUrl and paths options, cannot change the "@modules/DB" to "../modules/DB"? then,what does they do ?

like image 356
PengJu.Duan Avatar asked Oct 11 '17 13:10

PengJu.Duan


People also ask

What is true about Tsconfig json file?

json file is a file of JSON format which allows us to point the root level files and different compiler options to setup that require to compile a TypeScript based projects. The existence of this file in a project specifies that the given directory is the TypeScript project folder root.


1 Answers

The problem here is that the TypeScript compiler does not update the path in your JS files and the JavaScript Engine knows nothing about your TypeScript config, what you specify in your tsconfig is only used "compile time", when you have compiled your TypeScript into JS you need to do the same job as the TS compiler did but to save the resolved path in the JS file.

Simply put, all JS files needs to be processed and the aliases replaced with "real" paths.

People often suggest WebPack which is a monster, there are a really simple tool called tspath which your run in your project directory, it will read your tsconfig.json and update the JS source files accordingly!

Install tspath an npm tool for resolving ts paths NOTE: tspath requires a very recent versison of node!

npm install -g tspath

After you have run the TypeScript compiler, from your project directory, run:

tspath

or

tspath -f

to skip the prompt!

Read more at: https://www.npmjs.com/package/tspath

like image 81
Patrik Forsberg Avatar answered Oct 04 '22 22:10

Patrik Forsberg