Complete solution to build Nuxt Modules.
@nuxt/schemaCheck the new Guide for Nuxt Modules before starting with module-builder.
You can quickly get started with pre-configured module starter:
$ npx nuxi init -t module my-module
Using module builder, requires a special project setup. You can check an example here.
src/module.tsThis is the entrypoint for module definition.
A default export using defineNuxtModule and ModuleOptions type export is expected.
You could also optionally export ModuleHooks to annotate any custom hooks module uses.
import { defineNuxtModule } from '@nuxt/kit'
export interface ModuleOptions {
apiKey: string
}
export interface ModuleHooks {
'my-module:init': any
}
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'my-module',
configKey: 'myModule'
},
defaults: {
apiKey: 'test'
},
async setup (moduleOptions, nuxt) {
// Write module logic in setup function
}
})
src/runtime/Any runtime file and code that we need to provide by module including plugins, composables and server api, should be in this directory.
Each file will be transformed individually using unjs/mkdist to dist/runtime/.
package.json:A minimum package.json should look like this:
{
"name": "my-module",
"license": "MIT",
"version": "1.0.0",
"exports": {
".": {
"import": "./dist/module.mjs",
"require": "./dist/module.cjs"
}
},
"main": "./dist/module.cjs",
"types": "./dist/types.d.ts",
"files": [
"dist"
],
"scripts": {
"prepack": "nuxt-module-build"
},
"dependencies": {
"@nuxt/kit": "npm:@nuxt/kit-edge@latest"
},
"devDependencies": {
"@nuxt/module-builder": "latest"
}
}
Module builder generates dist files in dist/ directory:
module.mjs: Module entrypoint build from src/modulemodule.json: Module meta extracted from module.mjs + package.jsonmodule.cjs: ESM proxy to allow require module in CommonJS contexttypes.d.ts: Exported types in addition to shims for nuxt.config auto completion.runtime/*: Individually transformed files using unjs/mkdist
.ts files will be transformed to .mjs with extracted types on .d.ts file with same name.vue files will be transformed with extracted .d.ts filecorepack enable (use npm i -g corepack for Node.js < 16.10)yarn installyarn example:buildMIT - Made with 💚