Skip to content

Commit 17e8348

Browse files
authored
Expand out docs for noUncheckedSideEffectImports (#3223)
1 parent 9622166 commit 17e8348

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

packages/tsconfig-reference/copy/en/options/noUncheckedSideEffectImports.md

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,50 @@
22
display: "noUncheckedSideEffectImports"
33
oneline: "Check side effect imports."
44
---
5-
Check side effect imports.
6-
5+
6+
In JavaScript it's possible to `import` a module without actually importing any values from it.
7+
8+
```ts
9+
import "some-module";
10+
```
11+
12+
These imports are often called *side effect imports* because the only useful behavior they can provide is by executing some side effect (like registering a global variable, or adding a polyfill to a prototype).
13+
14+
By default, TypeScript will not check these imports for validity. If the import resolves to a valid source file, TypeScript will load and check the file.
15+
If no source file is found, TypeScript will silently ignore the import.
16+
17+
This is surprising behavior, but it partially stems from modeling patterns in the JavaScript ecosystem.
18+
For example, this syntax has also been used with special loaders in bundlers to load CSS or other assets.
19+
Your bundler might be configured in such a way where you can include specific `.css` files by writing something like the following:
20+
21+
```tsx
22+
import "./button-component.css";
23+
24+
export function Button() {
25+
// ...
26+
}
27+
```
28+
29+
Still, this masks potential typos on side effect imports.
30+
31+
When `--noUncheckedSideEffectImports` is enabled, TypeScript will error if it can't find a source file for a side effect import.
32+
33+
```ts
34+
import "oops-this-module-does-not-exist";
35+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
36+
// error: Cannot find module 'oops-this-module-does-not-exist' or its corresponding type declarations.
37+
```
38+
39+
When enabling this option, some working code may now receive an error, like in the CSS example above.
40+
To work around this, users who want to just write side effect `import`s for assets might be better served by writing what's called an *ambient module declaration* with a wildcard specifier.
41+
It would go in a global file and look something like the following:
42+
43+
```ts
44+
// ./src/globals.d.ts
45+
46+
// Recognize all CSS files as module imports.
47+
declare module "*.css" {}
48+
```
49+
50+
In fact, you might already have a file like this in your project!
51+
For example, running something like `vite init` might create a similar `vite-env.d.ts`.

0 commit comments

Comments
 (0)