简体   繁体   中英

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.

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. 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-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 .

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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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