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

前端 未结 1 2013
攒了一身酷
攒了一身酷 2021-02-12 21:14

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

相关标签:
1条回答
  • 2021-02-12 21:59

    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.

    0 讨论(0)
提交回复
热议问题