Trying to developer a mental model for what import * as Blah
does. For example:
import * as StackTrace from 'stacktrace-js';
How does that work and when do we do import *
?
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.
With TypeScript 3.8, you can import a type using the import statement, or using import type .
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
.
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.
Note also from the TypeScript Module doc:
Starting with ECMAScript 2015, JavaScript has a concept of modules. TypeScript shares this concept.
So TypeScript modules behave in the same way as ES6 JavaScript modules.
You would use import * as
in either TypeScript or JavaScript when you want access to all of the module exports in a single variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With