Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

node.js - Typescript2 path module resolution

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...