我是否必须在每个文件中引用typescript定义 [英] Do I have to reference typescript definition in every file

查看:138
本文介绍了我是否必须在每个文件中引用typescript定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉打字稿使用某个文件(或文件集)作为编译的所有内容的定义?

Is there a way to tell typescript to use a certain file (or set of files) as definition for everything compiled?

我目前唯一的选择是添加一些东西在每个打字稿文件(看起来很笨)中都是这样的:

My only alternative currently is to add something like this in every single typescript file (which seems clunky):

/// <reference path="DefinitelyTyped/requirejs/require.d.ts" />


推荐答案

使用TypeScript的内部模块系统时,可以避免代码中的所有< reference> 标签。我个人这样做是因为我不想在代码中对路径(实际或绝对)进行编码,因为我经常移动东西。

When using TypeScript's internal module system, you can avoid having any <reference> tags at all in the code. I personally do this because I don't want to encode paths (realtive or absolute) within the code as I constantly move stuff around.

一种方法是通过确保在编译期间将所有必需的声明文件和TypeScript源文件作为参数传递给编译器。

One way to do this is by making sure all required declaration files and TypeScript source files are passed to the compiler as arguments during compile time.

使用 gulp gulp-typescript 一起简化了这项任务。您可以将 gulp-typescript 中的 noExternalResolve 设置为true,并创建带有所有.d.ts文件的gulp任务与您的源和管道一起下载到编译器。当您将 tsd 拉入堆栈时,只需传递 tsd.d .ts 包含对通过 tsd 安装的所有其他定义文件的引用的文件。

Using gulp together with gulp-typescript simplifies this task. You can set noExternalResolve in gulp-typescript to true, and create gulp tasks that take all your .d.ts files along with your sources and pipe it down to the compiler. When you pull in tsd into your stack, you only need to pass the tsd.d.tsfile that contains references to all other definition files installed via tsd.

TypeScript的更新> = v1.5 :您可以使用 tsconfig .json 文件,编译器将获得正确的类的排序。这样就无需使用 gulp-typescript 。您可以选择在 tsconfig.json 文件中明确列出所有文件,也可以完全省略文件属性包含 tsconfig.json 所在目录中的所有 * .ts / * .tsx 文件(包括所有子文件夹) 。

UPDATE for TypeScript >= v1.5: you can use a tsconfig.json file, and the compiler will get the ordering of the classes right. This removes the need to use gulp-typescript alltogether. You can either chose to have all files explicitly listed in the tsconfig.json file, or completely leave out the files property to include all *.ts/*.tsx files within the directory the tsconfig.json resides (including all subfolders).

示例 tsconfig.json 可能如下所示:

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "lib": [ "es5", "es2015.promise", "dom" ]
    },
    "include": [
        "src/**/*.ts"
    ]
}

这篇关于我是否必须在每个文件中引用typescript定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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