Files
medusa-store/www/apps/book/app/basics/loaders/page.mdx
T

79 lines
1.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const metadata = {
title: `${pageNumber} Loaders`,
}
# {metadata.title}
In this chapter, youll learn about loaders and how to use them.
## What is a Loader?
A loader is a function executed when the Medusa application starts. You define and export it in a module.
Loaders are useful to perform a task at the application start-up, such as to sync data between Medusa and a third-pary service.
---
## How to Create a Loader?
A loader is created in a TypeScript or JavaScript file under a module's `loaders` directory.
For example, create the file `src/modules/hello/loaders/hello-world.ts` with the following content:
```ts title="src/modules/hello/loaders/hello-world.ts"
export default async function helloWorldLoader() {
console.log(
"[HELLO MODULE] Just started the Medusa application!"
)
}
```
### Export Loader in Module Definition
Import the loader in `src/modules/hello/index.ts` and export it in the module's definition:
```ts title="src/modules/hello/index.ts"
// other imports...
import helloWorldLoader from "./loaders/hello-world"
export default Module("hello", {
// ...
loaders: [helloWorldLoader],
})
```
The value of the `loaders` property is an array of loader functions.
---
## Test the Loader
Start the Medusa application:
```bash npm2yarn
npm run dev
```
Among the messages logged in the terminal, youll see the following message:
```bash
[HELLO MODULE] Just started the Medusa application!
```
---
## When to Use Loaders
<Note title="Use loaders when" type="success">
- You're performing an action at application start-up.
- You're establishing a one-time connection with an external system.
</Note>
<Note title="Don't use loaders if" type="error">
You want to perform an action continuously or at a set time pattern in the application. Use scheduled jobs instead, which is explained in an upcoming chapter.
</Note>