简体   繁体   English

我们什么时候使用 typescript import * as?

[英]When do we use typescript import * as?

Trying to developer a mental model for what import * as Blah does.试图import * as Blah所做的import * as Blah开发一个心理模型。 For example:例如:

import * as StackTrace from 'stacktrace-js';

How does that work and when do we do import * ?它是如何工作的,我们什么时候做import *

Not really an answer, but a usage: Consider you have a few constant strings to be used in your application, you can define them in a single file and export不是真正的答案,而是一种用法:考虑到您的应用程序中要使用一些常量字符串,您可以在单个文件中定义它们并导出

export const name = "NAME";
export const someOtherString = "SOME_CONST_STRING";

Then you can import them in a single variable using:然后您可以使用以下方法将它们导入到单个变量中:

import * as CONST_STRINGS from './yourFilePath';

and use as并用作

CONST_STRINGS.name 
CONST_STRINGS.someOtherString

From the TypeScript doc :打字稿文档

Import the entire module into a single variable, and use it to access the module exports将整个模块导入单个变量,并使用它来访问模块导出


The example code imports all exports of the stacktrace-js module into a variable called StackTrace .示例代码将stacktrace-js模块的所有导出导入到名为StackTrace的变量中。

Any named exports will be available as properties of the same name.任何命名的导出都将作为同名属性提供。

If the module has a default export it will be available as the default property.如果模块具有默认导出,它将可用作default属性。


Note also from the TypeScript Module doc :还请注意TypeScript 模块文档

Starting with ECMAScript 2015, JavaScript has a concept of modules.从 ECMAScript 2015 开始,JavaScript 有了模块的概念。 TypeScript shares this concept. TypeScript 共享这个概念。

So TypeScript modules behave in the same way as ES6 JavaScript modules.因此 TypeScript 模块的行为方式与 ES6 JavaScript 模块相同。


You would use import * as in either TypeScript or JavaScript when you want access to all of the module exports in a single variable.当您希望在单个变量中访问所有模块导出时,您可以import * as在 TypeScript 或 JavaScript 中import * as使用import * as

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM