If you have some code like this:
//other.js|ts
console.log("module sideffect")
export function foo() {
}
//main.js|ts
import {foo} from "./other"; // foo is not used
console.log("do something else");
Then JavaScript and TypeScript behave differently in this scenario.
TypesScript will omit the import of "./other"
, and the console.log("module sideeffect")
will not fire.
Whereas JavaScript will do the import and it will fire.
If on the other hand we do the import like:
import "./other";
The module side effects will fire.
There's a related question here:
Side effects in import statements
and here:
import module for side-effects with Typescript only targeting node
Which are both talking about this, but unfortunately both answers are now pointing to TypeScript documentation that no longer exists.
I'm looking for a canonical reason as to why TypeScript does this omission, and whether it's configurable behaviour. (One can imagine a scenario where code stops working because an import is no longer used).
If you have some code like this:
//other.js|ts
console.log("module sideffect")
export function foo() {
}
//main.js|ts
import {foo} from "./other"; // foo is not used
console.log("do something else");
Then JavaScript and TypeScript behave differently in this scenario.
TypesScript will omit the import of "./other"
, and the console.log("module sideeffect")
will not fire.
Whereas JavaScript will do the import and it will fire.
If on the other hand we do the import like:
import "./other";
The module side effects will fire.
There's a related question here:
Side effects in import statements
and here:
import module for side-effects with Typescript only targeting node
Which are both talking about this, but unfortunately both answers are now pointing to TypeScript documentation that no longer exists.
I'm looking for a canonical reason as to why TypeScript does this omission, and whether it's configurable behaviour. (One can imagine a scenario where code stops working because an import is no longer used).
Share Improve this question asked Mar 24 at 7:04 dwjohnstondwjohnston 12k39 gold badges117 silver badges218 bronze badges1 Answer
Reset to default 2whether it's configurable behaviour
The relevant option is verbatimModuleSyntax
. Its name is somewhat self-explanatory, and there are more details in the documentation if you follow that link, but in short it preserves all non-type
import
s as you wrote them.
a canonical reason as to why TypeScript does this omission
I couldn't find a concise explanation in the documentation, but the verbatimModuleSyntax
option's description has some rationale, as did the release notes for related features:
- Type-Only Imports and Export in 3.8
- Disabling Import Elision in 4.5
--verbatimModuleSyntax
in 5.0