## Module basics (Typescript)
🔹 *parent* [[⧋ Typescript|Typescript]]
▫️ *prev* [[⏶ Basic types|Basic types]], [[⏶ Union types|Union types]], [[⏶ Decorators and Dynamic Behavior (Typescript)|Decorators]]
### Module basics
Rather than loading each individual JS file in separately within the HTML, modules allow the ability to load one entrypoint which then references different modules which each have their own place in memory.
Without explicity defining import/export in a typescript file, it will throw errors when it encounters functions that haven't been explicity defined.
In `src/app.ts`
```ts
const formattedDate = formatDate(new Date()) // throws error
console.log(formattedDate)
```
In order to fix this, create the new `src/utils.ts` file where `formatDate()` will be defined.
```ts
// use export keyword
export function formatDate(date) {
return date.toLocaleDateString("en-US", {
dateStyle: "medium"
})
}
```
Then in `app.ts`
```ts
import { formatDate } from `./utils`
```
### Defining global types with ambient modules
create `globals.d.ts` in `/src`
In order to tell typescript that the following will be in the global namespace, add this:
```ts
declare global {
}
```
Notice that typescript will throw an error telling me that this has to be exported as a module:

This can be fixed by adding `export{}`
Note also that the commented code here will appear with intellisense.
```ts
declare global {
/** this formats a date value to a human-readable format */
function formatDate(date: Date): string
}
export {}
```
Now I have information on my function in my other module.

### Declaring merging
You can extend classes using an `interface` definition — even if a class is a third-party library. Standard JS does not allow you to do this. This is called *declaration merging*.
```ts
interface Customer {
/** saves the customer somewhere */
save(): void
}
// existing class
class Customer = {}
const customer = new Customer()
customer.save = function() {} // throws error without interface definition
```
With the interface, it now will give full type information

This is really useful when defining global functions that extend objects like `Window`.
```ts
const myVar = window.MY_VAR
```
In `globals.d.ts` define this `Window` property.
```ts
declare global {
interface Window {
/** this is my custom global variable */
MY_VAR: string
}
}
```
### Executing modular code
In order to run module code in node.js or the browser, the code must be defined differently.
Regular imports will throw this type of error:

In node.js, first set the `compilerOptions` to use `CommonJS`
```json
{
"compilerOptions": {
"target": "esnext",
"outDir": "dist",
"module": "CommonJS"
},
"include": [
"src/**/*"
]
}
```
Once compiled, it will convert the `import` to `require()`, which is what node uses to import.
For web apps, use either *Webpack* or *Parcel*.
### References
*see* [[⧋ Typescript#References|Typescript References]]