Typescript2 path module resolution
Asked Answered
W

1

11

tl;dr : module resolution does not apply ?

Hello,

I am playing around with Typescript2 module resolution feature.

I've noticed that it is now possible to specify "Paths", so that you can do the following :

Old way

import {a} from "../../../foo"

New way

import {a} from "services/foo"

To do so, you need to add some configs to your tsconfig.json

    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "services/*": ["./application/core/services/*"],
        }
    }

Problem that I have, is that when compiled, the import actually doesn't change. My javascript output still contains that import from "services/foo", so that obviously crash at runtime on my node server.

I use gulp-typescript to compile my javascript files :

var tsProject = ts.createProject("tsconfig.json");
return tsProject.src()
    .pipe(sourcemaps.init())
    .pipe(tsProject()).js
    .pipe(sourcemaps.write("../api"))
    .pipe(gulp.dest(function(file) {
        return file.base;
}));

I am completely lost here and would love to use that module resolution, so that I can move away from that ../../ hell of imports. Any help would be more than appreciated !

Waynant answered 13/2, 2017 at 6:3 Comment(0)
A
7

The problem here is that 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.

Tip: Use the npm tool tspath (https://www.npmjs.com/package/tspath), it requires 0 configuration, just run it in somewhere in your project and all JS files will be processed and ready to run!

Atterbury answered 14/1, 2018 at 1:54 Comment(5)
Is this still a problem in 2020 with TypeScript 3 and above? I'm having the same problem.Corporeal
@Corporeal Yeah, im having same issue atmBowerman
I had to use Babel. I couldn't find a way to get around this using only TypeScript.Corporeal
This dude mentioned something about tsconfig-paths, and it works perfectly for me (not to mention 7 millions downloads per week) github.com/microsoft/TypeScript/issues/…Jackscrew
Another option is to use module-alias. It works on runtime, so it is not needed to run anything. Just import it in the entry point of your code.Athanasius

© 2022 - 2024 — McMap. All rights reserved.