A lot of people have been asking me recently about recording a video crash course about building modules for Nuxt. As I have already created several nuxt modules, I thought that this is indeed a great idea! If you would like to check these modules, check out the bonus section at the end of this article.
So today, I come to you with my newest video tutorial as well as this written version of it so that you can follow easily.
In this crash course, I am showing how to build a simple Nuxt module that will allow to easily connect to Medusa
Module
To create this module, the first thing we need to do is to generate a new module template:
npx nuxi init -t module my-module
Then, go to the directory of this newly created module and lets install the Medusa JS SDK:
yarn add @medusajs/medusa-js
Now, let's go to the module.ts file and add all necessary configuration to make the module work.
import { defineNuxtModule, addPlugin, createResolver, addImportsDir } from '@nuxt/kit'
import { Config } from '@medusajs/medusa-js'
import defu from 'defu'
import { fileURLToPath } from 'url'
export type ModuleOptions = Config
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'nuxt-medusa',
configKey: 'medusa'
},
// Default configuration options of the Nuxt module
defaults: {
maxRetries: 3,
baseUrl: 'http://localhost:9000'
},
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.runtimeConfig.public.medusa = defu(nuxt.options.runtimeConfig.public.medusa, {
...options
})
addPlugin(resolver.resolve('./runtime/plugin'))
addImportsDir(resolver.resolve(runtimeDir, 'composables'))
}
})
In the video, I am explaining each step here so make sure to check it out for detailed explanation about each line and its purpose.
We have the configuration ready so let's focus now on initializing an actual Medusa client in our plugin.ts file:
import { defineNuxtPlugin } from '#app'
import { useRuntimeConfig } from '#imports'
import Medusa