【问题标题】:Is there a way to alias the import path in typescript有没有办法在打字稿中给导入路径起别名
【发布时间】:2014-11-26 15:35:40
【问题描述】:
import X = require('../../far/away/PathToX');
import Y = require('./another/path/PathToX');

我正在使用外部模块 (commonJS) 和 browserify,以及 WebStorm 作为编辑器。

如果这只是简单的 javascript,则有多种选项可以省略必须始终使用这些长路径,例如使用 browserify 别名。但是,使用 typescript 时,编辑器实际上会遵循路径并检索类型信息以提供智能感知。因此,如果我使用其中一个选项,编辑器将找不到文件路径,并且编译器也会引发错误。

那么打字稿(对于任何编辑器)中是否有任何现有方法允许我以某种方式使用路径别名?

【问题讨论】:

    标签: import module path typescript alias


    【解决方案1】:

    要做到这一点有一点技巧,但是您必须手动编写 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
            }
        }
    }
    

    或者使用define 而不是require

    就我个人而言,我会忍受漫长的路径,以便在不重写任何 TypeScript 的情况下使用 TypeScript 编译器开关来为我定位 AMD 或 CommonJS。

    【讨论】:

      【解决方案2】:

      那么打字稿(对于任何编辑器)中是否有任何现有方法允许我以某种方式使用路径别名?

      Grunt-ts 可以为你做到这一点。您通过ts:import=someFileName 进行简单引用,它将为您生成正确的import 语句https://github.com/TypeStrong/grunt-ts#import-transform

      【讨论】:

      • 虽然这可能意味着编辑器中没有实时智能感知,对吧?
      • 不适用于 filename 但将用于生成的基于 import 的类型
      猜你喜欢
      • 2021-11-29
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多