Typescript2 路径模块解析 [英] Typescript2 path module resolution

查看:16
本文介绍了Typescript2 路径模块解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tl;dr : 模块解析不适用?

tl;dr : module resolution does not apply ?

你好,

我正在玩 Typescript2 模块解析功能.

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 :

老办法

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

新方式

import {a} from "services/foo"

为此,您需要在 tsconfig.json 中添加一些配置

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

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

我遇到的问题是,在编译时,导入实际上并没有改变.我的 javascript 输出仍然包含来自services/foo"的导入,因此在我的节点服务器上运行时显然会崩溃.

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.

我使用 gulp-typescript 编译我的 javascript 文件:

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 !

推荐答案

这里的问题是 JavaScript 引擎对您的 TypeScript 配置一无所知,您在 tsconfig 中指定的内容仅在编译后使用编译时间"将 TypeScript 转换为 JS,您需要执行与 TS 编译器相同的工作,但将解析后的路径保存在 JS 文件中.

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.

简单地说,所有的JS文件都需要处理,别名替换为真实"路径.

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

提示:使用 npm 工具 tspath (https://www.npmjs.com/package/tspath),它需要0配置,只需在项目中的某个地方运行它,所有的JS文件都会被处理并准备好运行!

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!

这篇关于Typescript2 路径模块解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆