带有2.0库的Triple Slash Typescript参考

时间:2017-01-24 21:28:11

标签: typescript typescript2.0

我有一个最初基于Typescript 1.4构建的项目

它有一个主文件设置如下:

/// <reference path="typedefinitions/jquery/jquery.d.ts" />
/// <reference path="typedefinitions/jqueryui/jqueryui.d.ts" />
/// <reference path="typedefinitions/moment/moment.d.ts" />
module myApp {
   ...
}

所有其他文件只引用此主文件:

/// <reference path="../mainfile.ts" />
module myApp {
   //more code that can reference anything else in myApp
}

我们的构建过程的一部分将所有应用程序打字稿文件连接在一起,因此我们不使用任何模块加载器。

过去这种方法运行良好,但是,越来越多的库将其定义文件设置为import,并且使用上述方法引用它们不起作用。

ui-router为例,如果我添加:

/// <reference path="../node_modules/angular-ui-router/lib/index.d.ts"  />

引用的类型似乎没有出现在任何地方。如果我这样做:

import * as router from 'angular-ui-router';

然后所有其他文件都不能再引用'myApp'。

在重构我离开这种情况的同时还能将所有TS文件编译成单个javascript文件时,我最好的选择是什么?

我可以更改tsconfig设置吗?或者其他我想念的东西?

2 个答案:

答案 0 :(得分:3)

你有几个选择。

建议的方法

目前,摩擦力最小的选项包括一个捆绑器来处理您的单个文件需求,并使用ES6样式的模块系统来建立依赖关系(以前称为外部模块)。据我所知,命名空间系统尚未正式弃用,但在我看来,通过查看社区命名空间系统基本上已被放弃。它与import语句和@types系统不兼容,您将看到的大多数示例和代码都将使用它。完成此选项后,需要通过每个文件中的导入建立显式依赖项,而不是利用C#样式名称空间。

然后,您可以使用诸如systemjs,uglify,browserify等之类的东西来遍历依赖树并创建一个javascript包。原则上,有些人更喜欢这样做,纯粹是将编译任务从缩小和捆绑中分离出来。这也将解决您使用纯命名空间时可能遇到的一些乱序问题,因为每个文件(模块)都明确指定了它的确切依赖关系。

其他选项

您可以通过从DefinitelyTyped仓库手动下载.d.ts文件(或者当然使用打字,我会建议您遵循此路线)在短期内处理命名空间。现在有几个npm软件包在其依赖项中列出了@types软件包,因此您可能需要设置types: [] config属性以确保不使用@types,因此避免冲突。

虽然这仍然是一个可行的选择,但我建议采用ES6模块。这不是打字稿决定的问题,JS社区非常清楚地朝着这个方向发展,作为JS的超集,主要的结构JS决策将逐渐减少TS,这将成为默认。我觉得命名空间很快会成为遗留代码,有些人认为命名空间已经遗留下来了。

答案 1 :(得分:0)

Paarth,我想我会以类似于angular 2的方式处理这个问题,我将在其父组件中注册子组件:

hello.component.ts:

import Component from './component.decorator';

@Component('hello', {
    controllerAs: 'vm',
    template: '<div>Hi</div>'
})
export default class HelloComponent { }

app.component.ts:

import Component from './component.decorator';
import HelloComponent from './hello.component';

@Component('app', {
    controllerAs: 'vm',
    directives: [HelloComponent],
    template: `<div>
                <div>{{vm.Message}}</div>
                <hello></hello>
               </div>`
})
export class AppComponent {
    Message: string;

    $onInit() {
        this.Message = 'Hi!!!';
    }
}

component.decorator.ts:

import * as angular from 'angular';
import app from './main';

export interface ComponentBridgeOptions extends ng.IComponentOptions {
    directives?: any[];
}

export default function Component(selector: string, options: ComponentBridgeOptions) {
    return (controller: Function) => {
        app.component(selector, angular.extend(options, { controller: controller }));
    }
}