Typescript absolute module paths don't compile correctly

I'm relatively new to typescript, so maybe I am missing something or not fully understanding the concept. In tsconfig, I have defined the following in compilerOptions:

{
  baseUrl: ".",
  paths: {
    "*": ["server/*"]
  }
}
      

Run codeHide result


Assuming the following directory structure:

+ server
|  + routes
|  |  + util
|  |  - config.routes.ts
|  - route_file.ts
-tsconfig.json
      

Run codeHide result


If I import the module exported by route_file.ts in config.routes.ts:

import * as routes from 'routes/route_file.ts';
      

Run codeHide result


Typescript resolves the path without issue. However, compiled JS requires a module with the same literal path:

const routes = require('routes/route_file')
      

Run codeHide result


This is obviously a problem, because the module will not be found as the path must be .. / route_file. My project has quite a few subdirectories and I was hoping to get away from ../../../ if possible. Is there a way to force the compiler to check the directory of the import file and update the required path relative to that file?

+1


source to share


1 answer


The problem is that tsconfig tells the typescript compiler where the type information can be found. Path solving is a task for bundles like webpack. Or JavaScript runtime.
If you'd like to have a look at a working configuration using webpack, you can check out a sample with react I created a few weeks ago. https://github.com/kaoDev/react-ts-sample



0


source







All Articles