In TypeScript, when to use reference, when to use import?

有些话、适合烂在心里 提交于 2019-12-21 03:52:57

问题


in TypeScript there are two concepts of referencing files/modules. Even though I went briefly through TypeScript documentation it is unclear to me, when which approach should be used when:

  1. Triple-Slash reference: /// <reference path="..." />
  2. Import: import { Foo } from "./Foo";

Thanks


回答1:


It is important to understand that these are not two concepts to reference files/modules. Their actually two completely different things.

import

This keyword was introduces in ES2015 and thus is part of its implementation, which is JavaScript. It doesn't only reference a file/module, but rather it reads the referenced module and makes its API/exposed stuff available to you.

Before import we had to use some sort of concat mechanism or use <link> in the HTML to get access to say jQuery. Now we can do import * as $ from 'jQuery' and JavaScript/TypeScript will "automatically" load the module for us. At least this is what it will do in the future as soon the Loader is finished.

If you're using TypeScript the TypeScript compiler will also know what types/signatures/... exported the code has.

/// <reference>

The little bit weird <reference> comment was used to pull in type definitions from external .d.ts files. But with a newer version of TypeScript you shouldn't need to do this anymore. You can read about the future of decalration files here.

So the difference between import and <reference> is that import will load the "real" code and make it available to you. <reference> on the other hand will only import type definitions for you. In your editor/IDE it will look like you're using the code, but actually TypeScript knows about the exposed APIs and pretends that actually can use the loaded module. It will be your job to make the module (globally) available when you want to run your code.




回答2:


<reference /> is useful when working with namespaces.



来源:https://stackoverflow.com/questions/39121354/in-typescript-when-to-use-reference-when-to-use-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!