Typescript2 path module resolution

拥有回忆 提交于 2019-11-28 04:38:47

问题


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 !


回答1:


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!



来源:https://stackoverflow.com/questions/42197563/typescript2-path-module-resolution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!