简体   繁体   English

有没有办法在打字稿中别名导入路径

[英]Is there a way to alias the import path in typescript

import X = require('../../far/away/PathToX');
import Y = require('./another/path/PathToX');

I'm using external modules (commonJS) and browserify, and WebStorm as editor. 我正在使用外部模块(commonJS)和browserify,并使用WebStorm作为编辑器。

If this were just plain javascript, there are various options to omit having to use these long paths all the time, for example with browserify aliases. 如果这只是普通的javascript,则可以使用各种选项来忽略必须始终使用这些长路径,例如使用browserify别名。 However, with typescript the editor actually follows the path and retreives type information to give intellisense. 但是,使用打字稿时,编辑器实际上会遵循该路径并检索打字信息以提供智能感知。 So if I use one of those options, the editor can't find the filepath, and also the compiler raises an error. 因此,如果使用这些选项之一,则编辑器将找不到文件路径,并且编译器也会引发错误。

So are there any existing ways in typescript (for any editor) that allow me to use path aliases in some way? 那么打字稿中是否有任何现有方法(适用于任何编辑器)允许我以某种方式使用路径别名?

There is a bit of a hack to do it, but you would have to manually write either the AMD or CommonJS import... for example, like this... 有一点技巧可以做到,但是您必须手动编写AMD或CommonJS导入...例如,像这样...

///<amd-dependency path="scripts/typings/cordova/cordova.d.ts" />
declare var require: any;

var cordova: Cordova = require('cordova');

module Example {

    class Test {

        constructor() {
            cordova.exec(this.success, this.error, "Service", "Action", null);
        }

        private success(message?: string) {
            //do Something
        }

        private error(message?: string) {
            //do Something
        }
    }
}

Or using define rather than require . 或者使用define而不是require

Personally, I would live with the long paths to get the benefit of using the TypeScript compiler switch to target AMD or CommonJS for me without re-writing any TypeScript. 就我个人而言,我会走很长的路,以获得使用TypeScript编译器开关为我定位AMD或CommonJS的好处,而无需重写任何TypeScript。

So are there any existing ways in typescript (for any editor) that allow me to use path aliases in some way? 那么打字稿中是否有任何现有方法(适用于任何编辑器)允许我以某种方式使用路径别名?

Grunt-ts can do this for you. Grunt-ts可以为您做到这一点。 You simple reference by ts:import=someFileName and it will generate the correct import statement for you https://github.com/TypeStrong/grunt-ts#import-transform 您可以通过ts:import=someFileName简单引用,它将为您生成正确的import语句https://github.com/TypeStrong/grunt-ts#import-transform

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM