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

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

问题描述

tl; dr:模块分辨率不适用?



您好,



Typescript2模块分辨率功能。



我注意到现在可以指定路径,以便您可以执行以下操作:

旧式

 从{../ ../../foo

新方法


$ b $

 从services / foo导入{a} 

要做到这一点,你需要在你的tsconfig.json中添加一些配置
$ b

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


$ / code>

问题是,编译时,导入实际上不会改变。我的javascript输出仍然包含从services / foo导入,所以显然在运行时崩溃在我的节点服务器上。



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

  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;
}));

我完全迷失在这里,很想使用模块分辨率,这样我就可以离开那../../地狱的进口。任何帮助都将不胜感激!

解决方案

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



简单地说,所有的JS文件都需要被处理,别名被替换为真实路径。 提示:使用npm工具tspath ( https://www.npmjs.com/package/tspath ),它需要0个配置,只需在你的项目中的某处运行它,所有的JS文件将被处理并准备运行!


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 !

解决方案

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!

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

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