diff --git a/src/content/9/en/part9c.md b/src/content/9/en/part9c.md index 82b35715fcb..b92994a214f 100644 --- a/src/content/9/en/part9c.md +++ b/src/content/9/en/part9c.md @@ -603,6 +603,57 @@ export interface DiaryEntry { } ``` +### Node and JSON modules + +It is important to take note of a problem that may arise when using the tsconfig [resolveJsonModule](https://www.typescriptlang.org/en/tsconfig#resolveJsonModule) option: + +```json +{ + "compilerOptions": { + // ... + "resolveJsonModule": true // highlight-line + } +} +``` + +According to the node documentation for [file modules](https://nodejs.org/api/modules.html#modules_file_modules), +node will try to resolve modules in order of extensions: + +```sh + ["js", "json", "node"] +``` + +In addition to that, by default, ts-node and ts-node-dev extend the list of possible node module extensions to: + +```sh + ["js", "json", "node", "ts", "tsx"] +``` + +> **NB**: The validity of .js, .json and .node files as modules in Typescript depend on environment configuration, including tsconfig options such as allowJs and resolveJsonModule. + +Consider a flat folder structure containing files: + +```sh + ├── myModule.json + └── myModule.ts +``` + +In typescript, with the resolveJsonModule option set to true, the file myModule.json becomes a valid node module. Now, imagine a scenario where we wish to take the file myModule.ts into use: + +```js +import myModule from "./myModule"; +``` + +Looking closely at the order of node module extensions: + +```sh + ["js", "json", "node", "ts", "tsx"] +``` + +We notice that the .json file extension takes precedence over .ts and so myModule.json will be imported and not myModule.ts. + +In order to avoid time eating bugs, it is recommended that within a flat directory, each file with a valid node module extension has a unique filename. + ### Utility Types