5.9. Custom CLI Scripts

In this chapter, you'll learn how to create and execute custom scripts from Medusa's CLI tool.

What is a Custom CLI Script?#

A custom CLI script is a function to execute through Medusa's CLI tool. This is useful when creating custom Medusa tooling to run through the CLI.


How to Create a Custom CLI Script?#

To create a custom CLI script, create a TypeScript or JavaScript file under the src/scripts directory. The file must default export a function.

For example, create the file src/scripts/my-script.ts with the following content:

src/scripts/my-script.ts
1import { 2  ExecArgs,3  IProductModuleService,4} from "@medusajs/framework/types"5import { Modules } from "@medusajs/framework/utils"6
7export default async function myScript({ container }: ExecArgs) {8  const productModuleService: IProductModuleService = container.resolve(9    Modules.PRODUCT10  )11
12  const [, count] = await productModuleService13    .listAndCountProducts()14
15  console.log(`You have ${count} product(s)`)16}

The function receives as a parameter an object having a container property, which is an instance of the Medusa Container. Use it to resolve resources in your Medusa application.


How to Run Custom CLI Script?#

To run the custom CLI script, run the Medusa CLI's exec command:

Terminal
npx medusa exec ./src/scripts/my-script.ts

Custom CLI Script Arguments#

Your script can accept arguments from the command line. Arguments are passed to the function's object parameter in the args property.

For example:

Code
1import { ExecArgs } from "@medusajs/framework/types"2
3export default async function myScript({ args }: ExecArgs) {4  console.log(`The arguments you passed: ${args}`)5}

Then, pass the arguments in the exec command after the file path:

Terminal
npx medusa exec ./src/scripts/my-script.ts arg1 arg2
Was this chapter helpful?
Edit this page