@nuxt/docs 3.17.1 → 3.17.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/1.getting-started/01.introduction.md +1 -1
  2. package/1.getting-started/02.installation.md +8 -0
  3. package/1.getting-started/03.configuration.md +1 -1
  4. package/1.getting-started/07.routing.md +1 -1
  5. package/1.getting-started/15.prerendering.md +2 -2
  6. package/1.getting-started/16.deployment.md +2 -2
  7. package/1.getting-started/18.upgrade.md +42 -3
  8. package/2.guide/1.concepts/1.auto-imports.md +1 -1
  9. package/2.guide/1.concepts/3.rendering.md +2 -2
  10. package/2.guide/1.concepts/4.server-engine.md +1 -1
  11. package/2.guide/2.directory-structure/1.server.md +6 -6
  12. package/2.guide/3.going-further/1.events.md +82 -0
  13. package/2.guide/3.going-further/11.nightly-release-channel.md +1 -3
  14. package/2.guide/3.going-further/2.hooks.md +1 -20
  15. package/2.guide/3.going-further/3.modules.md +1 -1
  16. package/3.api/2.composables/use-request-url.md +2 -2
  17. package/3.api/3.utils/navigate-to.md +1 -1
  18. package/3.api/5.kit/1.modules.md +105 -92
  19. package/3.api/5.kit/10.runtime-config.md +2 -0
  20. package/3.api/5.kit/10.templates.md +187 -163
  21. package/3.api/5.kit/11.nitro.md +207 -168
  22. package/3.api/5.kit/12.resolving.md +79 -133
  23. package/3.api/5.kit/13.logging.md +19 -29
  24. package/3.api/5.kit/14.builder.md +140 -373
  25. package/3.api/5.kit/2.programmatic.md +11 -64
  26. package/3.api/5.kit/3.compatibility.md +88 -135
  27. package/3.api/5.kit/4.autoimports.md +3 -3
  28. package/3.api/5.kit/5.components.md +22 -3
  29. package/3.api/5.kit/6.context.md +92 -48
  30. package/3.api/5.kit/7.pages.md +95 -197
  31. package/3.api/5.kit/8.layout.md +68 -49
  32. package/3.api/5.kit/9.plugins.md +140 -139
  33. package/3.api/6.advanced/1.hooks.md +1 -1
  34. package/package.json +1 -1
@@ -48,7 +48,7 @@ disable SSR globally with the `ssr: false` option or leverage hybrid rendering b
48
48
 
49
49
  ### Server engine
50
50
 
51
- The Nuxt server engine [Nitro](https://nitro.unjs.io) unlocks new full-stack capabilities.
51
+ The Nuxt server engine [Nitro](https://nitro.build/) unlocks new full-stack capabilities.
52
52
 
53
53
  In development, it uses Rollup and Node.js workers for your server code and context isolation. It also generates your server API by reading files in `server/api/` and server middleware from `server/middleware/`.
54
54
 
@@ -54,6 +54,10 @@ pnpm create nuxt <project-name>
54
54
  bun create nuxt <project-name>
55
55
  ```
56
56
 
57
+ ```bash [deno]
58
+ deno -A npm:create-nuxt@latest <project-name>
59
+ ```
60
+
57
61
  ::
58
62
 
59
63
  ::tip
@@ -96,6 +100,10 @@ bun run dev -o
96
100
  # To use the Bun runtime during development
97
101
  # bun --bun run dev -o
98
102
  ```
103
+
104
+ ```bash [deno]
105
+ deno run dev -o
106
+ ```
99
107
  ::
100
108
 
101
109
  ::tip{icon="i-lucide-circle-check"}
@@ -149,7 +149,7 @@ Nuxt uses [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt-config) file a
149
149
 
150
150
  Name | Config File | How To Configure
151
151
  ---------------------------------------------|---------------------------|-------------------------
152
- [Nitro](https://nitro.unjs.io) | ~~`nitro.config.ts`~~ | Use [`nitro`](/docs/api/nuxt-config#nitro) key in `nuxt.config`
152
+ [Nitro](https://nitro.build) | ~~`nitro.config.ts`~~ | Use [`nitro`](/docs/api/nuxt-config#nitro) key in `nuxt.config`
153
153
  [PostCSS](https://postcss.org) | ~~`postcss.config.js`~~ | Use [`postcss`](/docs/api/nuxt-config#postcss) key in `nuxt.config`
154
154
  [Vite](https://vite.dev) | ~~`vite.config.ts`~~ | Use [`vite`](/docs/api/nuxt-config#vite) key in `nuxt.config`
155
155
  [webpack](https://webpack.js.org) | ~~`webpack.config.ts`~~ | Use [`webpack`](/docs/api/nuxt-config#webpack-1) key in `nuxt.config`
@@ -131,7 +131,7 @@ definePageMeta({
131
131
 
132
132
  Nuxt offers route validation via the `validate` property in [`definePageMeta()`](/docs/api/utils/define-page-meta) in each page you wish to validate.
133
133
 
134
- The `validate` property accepts the `route` as an argument. You can return a boolean value to determine whether or not this is a valid route to be rendered with this page. If you return `false`, and another match can't be found, this will cause a 404 error. You can also directly return an object with `statusCode`/`statusMessage` to respond immediately with an error (other matches will not be checked).
134
+ The `validate` property accepts the `route` as an argument. You can return a boolean value to determine whether or not this is a valid route to be rendered with this page. If you return `false`, this will cause a 404 error. You can also directly return an object with `statusCode`/`statusMessage` to customize the error returned.
135
135
 
136
136
  If you have a more complex use case, then you can use anonymous route middleware instead.
137
137
 
@@ -79,7 +79,7 @@ export default defineNuxtConfig({
79
79
 
80
80
  Setting `nitro.prerender` to `true` is similar to `nitro.prerender.crawlLinks` to `true`.
81
81
 
82
- ::read-more{to="https://nitro.unjs.io/config#prerender"}
82
+ ::read-more{to="https://nitro.build/config#prerender"}
83
83
  Read more about pre-rendering in the Nitro documentation.
84
84
  ::
85
85
 
@@ -99,7 +99,7 @@ export default defineNuxtConfig({
99
99
  });
100
100
  ```
101
101
 
102
- ::read-more{to="https://nitro.unjs.io/config/#routerules"}
102
+ ::read-more{to="https://nitro.build/config/#routerules"}
103
103
  Read more about Nitro's `routeRules` configuration.
104
104
  ::
105
105
 
@@ -62,7 +62,7 @@ By default, the workload gets distributed to the workers with the round robin st
62
62
 
63
63
  ### Learn More
64
64
 
65
- :read-more{to="https://nitro.unjs.io/deploy/node" title="the Nitro documentation for node-server preset"}
65
+ :read-more{to="https://nitro.build/deploy/node" title="the Nitro documentation for node-server preset"}
66
66
 
67
67
  :video-accordion{title="Watch Daniel Roe's short video on the topic" videoId="0x1H6K5yOfs"}
68
68
 
@@ -111,7 +111,7 @@ export default defineNuxtConfig({
111
111
  NITRO_PRESET=node-server nuxt build
112
112
  ```
113
113
 
114
- 🔎 Check [the Nitro deployment](https://nitro.unjs.io/deploy) for all possible deployment presets and providers.
114
+ 🔎 Check [the Nitro deployment](https://nitro.build/deploy) for all possible deployment presets and providers.
115
115
 
116
116
  ## CDN Proxy
117
117
 
@@ -35,9 +35,7 @@ bun x nuxi upgrade
35
35
  To use the latest Nuxt build and test features before their release, read about the [nightly release channel](/docs/guide/going-further/nightly-release-channel) guide.
36
36
 
37
37
  ::warning
38
- The nightly release channel `latest` tag is currently tracking the Nuxt v4 branch, meaning that it is particularly likely to have breaking changes right now - be careful!
39
-
40
- You can opt in to the 3.x branch nightly releases with `"nuxt": "npm:nuxt-nightly@3x"`.
38
+ The nightly release channel `latest` tag is currently tracking the Nuxt v4 branch, meaning that it is particularly likely to have breaking changes right now &mdash; be careful! You can opt in to the 3.x branch nightly releases with `"nuxt": "npm:nuxt-nightly@3x"`.
41
39
  ::
42
40
 
43
41
  ## Testing Nuxt 4
@@ -76,6 +74,7 @@ export default defineNuxtConfig({
76
74
  // spaLoadingTemplateLocation: 'within',
77
75
  // parseErrorData: false,
78
76
  // pendingWhenIdle: true,
77
+ // alwaysRunFetchOnKeyChange: true,
79
78
  // defaults: {
80
79
  // useAsyncData: {
81
80
  // deep: true
@@ -752,6 +751,46 @@ export default defineNuxtConfig({
752
751
  })
753
752
  ```
754
753
 
754
+ ### Key Change Behavior in `useAsyncData` and `useFetch`
755
+
756
+ 🚦 **Impact Level**: Medium
757
+
758
+ #### What Changed
759
+
760
+ When using reactive keys in `useAsyncData` or `useFetch`, Nuxt automatically refetches data when the key changes. When `immediate: false` is set, `useAsyncData` will only fetch data when the key changes if the data has already been fetched once.
761
+
762
+ Previously, `useFetch` had slightly different behavior. It would always fetch data when the key changed.
763
+
764
+ Now, `useFetch` and `useAsyncData` behave consistently - by only fetch data when the key changes if the data has already been fetched once.
765
+
766
+ #### Reasons for Change
767
+
768
+ This ensures consistent behavior between `useAsyncData` and `useFetch`, and prevents unexpected fetches. If you have set `immediate: false`, then you must call `refresh` or `execute` or data will never be fetched in `useFetch` or `useAsyncData`.
769
+
770
+ #### Migration Steps
771
+
772
+ This change should generally improve the expected behavior, but if you were expecting changing the key or options of a non-immediate `useFetch`, you now will need to trigger it manually the first time.
773
+
774
+ ```diff
775
+ const id = ref('123')
776
+ const { data, execute } = await useFetch('/api/test', {
777
+ query: { id },
778
+ immediate: false
779
+ )
780
+ + watch(id, execute, { once: true })
781
+ ```
782
+
783
+ To opt out of this behavior:
784
+
785
+ ```ts
786
+ // Or globally in your Nuxt config
787
+ export default defineNuxtConfig({
788
+ experimental: {
789
+ alwaysRunFetchOnKeyChange: true
790
+ }
791
+ })
792
+ ```
793
+
755
794
  ### Shallow Data Reactivity in `useAsyncData` and `useFetch`
756
795
 
757
796
  🚦 **Impact Level**: Minimal
@@ -54,7 +54,7 @@ const double = computed(() => count.value * 2)
54
54
 
55
55
  When you are using the built-in Composition API composables provided by Vue and Nuxt, be aware that many of them rely on being called in the right _context_.
56
56
 
57
- During a component lifecycle, Vue tracks the temporary instance of the current component (and similarly, Nuxt tracks a temporary instance of `nuxtApp`) via a global variable, and then unsets it in same tick. This is essential when server rendering, both to avoid cross-request state pollution (leaking a shared reference between two users) and to avoid leakage between different components.
57
+ During a component lifecycle, Vue tracks the temporary instance of the current component (and similarly, Nuxt tracks a temporary instance of `nuxtApp`) via a global variable, and then unsets it in the same tick. This is essential when server rendering, both to avoid cross-request state pollution (leaking a shared reference between two users) and to avoid leakage between different components.
58
58
 
59
59
  That means that (with very few exceptions) you cannot use them outside a Nuxt plugin, Nuxt route middleware or Vue setup function. On top of that, you must use them synchronously - that is, you cannot use `await` before calling a composable, except within `<script setup>` blocks, within the setup function of a component declared with `defineNuxtComponent`, in `defineNuxtPlugin` or in `defineNuxtRouteMiddleware`, where we perform a transform to keep the synchronous context even after the `await`.
60
60
 
@@ -152,7 +152,7 @@ Previously every route/page of a Nuxt application and server must use the same r
152
152
 
153
153
  Nuxt includes route rules and hybrid rendering support. Using route rules you can define rules for a group of nuxt routes, change rendering mode or assign a cache strategy based on route!
154
154
 
155
- Nuxt server will automatically register corresponding middleware and wrap routes with cache handlers using [Nitro caching layer](https://nitro.unjs.io/guide/cache).
155
+ Nuxt server will automatically register corresponding middleware and wrap routes with cache handlers using [Nitro caching layer](https://nitro.build/guide/cache).
156
156
 
157
157
  ```ts twoslash [nuxt.config.ts]
158
158
  export default defineNuxtConfig({
@@ -219,7 +219,7 @@ With ESR, the rendering process is pushed to the 'edge' of the network - the CDN
219
219
 
220
220
  When a request for a page is made, instead of going all the way to the original server, it's intercepted by the nearest edge server. This server generates the HTML for the page and sends it back to the user. This process minimizes the physical distance the data has to travel, **reducing latency and loading the page faster**.
221
221
 
222
- Edge-side rendering is possible thanks to [Nitro](https://nitro.unjs.io), the [server engine](/docs/guide/concepts/server-engine) that powers Nuxt. It offers cross-platform support for Node.js, Deno, Cloudflare Workers, and more.
222
+ Edge-side rendering is possible thanks to [Nitro](https://nitro.build/), the [server engine](/docs/guide/concepts/server-engine) that powers Nuxt. It offers cross-platform support for Node.js, Deno, Cloudflare Workers, and more.
223
223
 
224
224
  The current platforms where you can leverage ESR are:
225
225
  - [Cloudflare Pages](https://pages.cloudflare.com) with zero configuration using the git integration and the `nuxt build` command
@@ -3,7 +3,7 @@ title: Server Engine
3
3
  description: 'Nuxt is powered by a new server engine: Nitro.'
4
4
  ---
5
5
 
6
- While building Nuxt, we created a new server engine: [Nitro](https://nitro.unjs.io).
6
+ While building Nuxt, we created a new server engine: [Nitro](https://nitro.build/).
7
7
 
8
8
  It is shipped with many features:
9
9
 
@@ -97,7 +97,7 @@ export default defineNitroPlugin((nitroApp) => {
97
97
  })
98
98
  ```
99
99
 
100
- :read-more{to="https://nitro.unjs.io/guide/plugins" title="Nitro Plugins" target="_blank"}
100
+ :read-more{to="https://nitro.build/guide/plugins" title="Nitro Plugins" target="_blank"}
101
101
 
102
102
  ## Server Utilities
103
103
 
@@ -160,7 +160,7 @@ export default defineEventHandler((event) => {
160
160
  })
161
161
  ```
162
162
 
163
- ::tip{to="https://h3.unjs.io/examples/validate-data#validate-params"}
163
+ ::tip{to="https://h3.dev/examples/validate-data#validate-params"}
164
164
  Alternatively, use `getValidatedRouterParams` with a schema validator such as Zod for runtime and type safety.
165
165
  ::
166
166
 
@@ -389,7 +389,7 @@ export default eventHandler((event) => {
389
389
 
390
390
  ### Nitro Config
391
391
 
392
- You can use `nitro` key in `nuxt.config` to directly set [Nitro configuration](https://nitro.unjs.io/config).
392
+ You can use `nitro` key in `nuxt.config` to directly set [Nitro configuration](https://nitro.build/config).
393
393
 
394
394
  ::warning
395
395
  This is an advanced option. Custom config can affect production deployments, as the configuration interface might change over time when Nitro is upgraded in semver-minor versions of Nuxt.
@@ -397,7 +397,7 @@ This is an advanced option. Custom config can affect production deployments, as
397
397
 
398
398
  ```ts [nuxt.config.ts]
399
399
  export default defineNuxtConfig({
400
- // https://nitro.unjs.io/config
400
+ // https://nitro.build/config
401
401
  nitro: {}
402
402
  })
403
403
  ```
@@ -464,7 +464,7 @@ Never combine `next()` callback with a legacy middleware that is `async` or retu
464
464
 
465
465
  ### Server Storage
466
466
 
467
- Nitro provides a cross-platform [storage layer](https://nitro.unjs.io/guide/storage). In order to configure additional storage mount points, you can use `nitro.storage`, or [server plugins](#server-plugins).
467
+ Nitro provides a cross-platform [storage layer](https://nitro.build/guide/storage). In order to configure additional storage mount points, you can use `nitro.storage`, or [server plugins](#server-plugins).
468
468
 
469
469
  **Example of adding a Redis storage:**
470
470
 
@@ -506,7 +506,7 @@ export default defineEventHandler(async (event) => {
506
506
  })
507
507
  ```
508
508
 
509
- ::read-more{to="https://nitro.unjs.io/guide/storage" target="_blank"}
509
+ ::read-more{to="https://nitro.build/guide/storage" target="_blank"}
510
510
  Read more about Nitro Storage Layer.
511
511
  ::
512
512
 
@@ -0,0 +1,82 @@
1
+ ---
2
+ title: "Events"
3
+ description: "Nuxt provides a powerful event system powered by hookable."
4
+ ---
5
+
6
+ # Events
7
+
8
+ Using events is a great way to decouple your application and allow for more flexible and modular communication between different parts of your code. Events can have multiple listeners that do not depend on each other. For example, you may wish to send an email to your user each time an order has shipped. Instead of coupling your order processing code to your email code, you can emit an event which a listener can receive and use to dispatch an email.
9
+
10
+ The Nuxt event system is powered by [unjs/hookable](https://github.com/unjs/hookable), which is the same library that powers the Nuxt hooks system.
11
+
12
+ ## Creating Events and Listeners
13
+
14
+ You can create your own custom events using the `hook` method:
15
+
16
+ ```ts
17
+ const nuxtApp = useNuxtApp()
18
+
19
+ nuxtApp.hook('app:user:registered', payload => {
20
+ console.log('A new user has registered!', payload)
21
+ })
22
+ ```
23
+
24
+ To emit an event and notify any listeners, use `callHook`:
25
+
26
+ ```ts
27
+ const nuxtApp = useNuxtApp()
28
+
29
+ await nuxtApp.callHook('app:user:registered', {
30
+ id: 1,
31
+ name: 'John Doe',
32
+ })
33
+ ```
34
+
35
+ You can also use the payload object to enable two-way communication between the emitter and listeners. Since the payload is passed by reference, a listener can modify it to send data back to the emitter.
36
+
37
+ ```ts
38
+ const nuxtApp = useNuxtApp()
39
+
40
+ nuxtApp.hook('app:user:registered', payload => {
41
+ payload.message = 'Welcome to our app!'
42
+ })
43
+
44
+ const payload = {
45
+ id: 1,
46
+ name: 'John Doe',
47
+ }
48
+
49
+ await nuxtApp.callHook('app:user:registered', {
50
+ id: 1,
51
+ name: 'John Doe',
52
+ })
53
+
54
+ // payload.message will be 'Welcome to our app!'
55
+ ```
56
+
57
+ ::tip
58
+ You can inspect all events using the **Nuxt DevTools** Hooks panel.
59
+ ::
60
+
61
+ ## Augmenting Types
62
+
63
+ You can augment the types of hooks provided by Nuxt.
64
+
65
+ ```ts
66
+ import { HookResult } from "@nuxt/schema";
67
+
68
+ declare module '#app' {
69
+ interface RuntimeNuxtHooks {
70
+ 'your-nuxt-runtime-hook': () => HookResult
71
+ }
72
+ interface NuxtHooks {
73
+ 'your-nuxt-hook': () => HookResult
74
+ }
75
+ }
76
+
77
+ declare module 'nitropack' {
78
+ interface NitroRuntimeHooks {
79
+ 'your-nitro-hook': () => void;
80
+ }
81
+ }
82
+ ```
@@ -16,9 +16,7 @@ Features that are only available on the nightly release channel are marked with
16
16
  ::
17
17
 
18
18
  ::warning
19
- The `latest` nightly release channel is currently tracking the Nuxt v4 branch, meaning that it is particularly likely to have breaking changes right now - be careful!
20
-
21
- You can opt in to the 3.x branch nightly releases with `"nuxt": "npm:nuxt-nightly@3x"`.
19
+ The `latest` nightly release channel is currently tracking the Nuxt v4 branch, meaning that it is particularly likely to have breaking changes right now &mdash; be careful! You can opt in to the 3.x branch nightly releases with `"nuxt": "npm:nuxt-nightly@3x"`.
22
20
  ::
23
21
 
24
22
  ## Opting In
@@ -76,23 +76,4 @@ Learn more about available Nitro lifecycle hooks.
76
76
 
77
77
  ## Additional Hooks
78
78
 
79
- You can add additional hooks by augmenting the types provided by Nuxt. This can be useful for modules.
80
-
81
- ```ts
82
- import { HookResult } from "@nuxt/schema";
83
-
84
- declare module '#app' {
85
- interface RuntimeNuxtHooks {
86
- 'your-nuxt-runtime-hook': () => HookResult
87
- }
88
- interface NuxtHooks {
89
- 'your-nuxt-hook': () => HookResult
90
- }
91
- }
92
-
93
- declare module 'nitropack' {
94
- interface NitroRuntimeHooks {
95
- 'your-nitro-hook': () => void;
96
- }
97
- }
98
- ```
79
+ Learn more about creating custom hooks in the [Events section](/docs/guide/going-further/events).
@@ -24,7 +24,7 @@ yarn create nuxt -t module my-module
24
24
  ```
25
25
 
26
26
  ```bash [pnpm]
27
- pnpm create nuxt -- -t module my-module
27
+ pnpm create nuxt -t module my-module
28
28
  ```
29
29
 
30
30
  ```bash [bun]
@@ -11,9 +11,9 @@ links:
11
11
  `useRequestURL` is a helper function that returns an [URL object](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) working on both server-side and client-side.
12
12
 
13
13
  ::important
14
- When utilizing [Hybrid Rendering](/docs/guide/concepts/rendering#hybrid-rendering) with cache strategies, all incoming request headers are dropped when handling the cached responses via the [Nitro caching layer](https://nitro.unjs.io/guide/cache) (meaning `useRequestURL` will return `localhost` for the `host`).
14
+ When utilizing [Hybrid Rendering](/docs/guide/concepts/rendering#hybrid-rendering) with cache strategies, all incoming request headers are dropped when handling the cached responses via the [Nitro caching layer](https://nitro.build/guide/cache) (meaning `useRequestURL` will return `localhost` for the `host`).
15
15
 
16
- You can define the [`cache.varies` option](https://nitro.unjs.io/guide/cache#options) to specify headers that will be considered when caching and serving the responses, such as `host` and `x-forwarded-host` for multi-tenant environments.
16
+ You can define the [`cache.varies` option](https://nitro.build/guide/cache#options) to specify headers that will be considered when caching and serving the responses, such as `host` and `x-forwarded-host` for multi-tenant environments.
17
17
  ::
18
18
 
19
19
  ::code-group
@@ -17,7 +17,7 @@ Make sure to always use `await` or `return` on result of `navigateTo` when calli
17
17
  ::
18
18
 
19
19
  ::note
20
- `navigateTo` cannot be used within Nitro routes. To perform a server-side redirect in Nitro routes, use [`sendRedirect`](https://h3.unjs.io/utils/response#sendredirectevent-location-code) instead.
20
+ `navigateTo` cannot be used within Nitro routes. To perform a server-side redirect in Nitro routes, use [`sendRedirect`](https://h3.dev/utils/response#sendredirectevent-location-code) instead.
21
21
  ::
22
22
 
23
23
  ### Within a Vue Component
@@ -14,87 +14,57 @@ Modules are the building blocks of Nuxt. Kit provides a set of utilities to help
14
14
 
15
15
  Define a Nuxt module, automatically merging defaults with user provided options, installing any hooks that are provided, and calling an optional setup function for full control.
16
16
 
17
- ### Type
17
+ ### Usage
18
18
 
19
- ```ts
20
- function defineNuxtModule<OptionsT extends ModuleOptions> (definition: ModuleDefinition<OptionsT> | NuxtModule<OptionsT>): NuxtModule<OptionsT>
21
-
22
- type ModuleOptions = Record<string, any>
23
-
24
- interface ModuleDefinition<T extends ModuleOptions = ModuleOptions> {
25
- meta?: ModuleMeta
26
- defaults?: T | ((nuxt: Nuxt) => T)
27
- schema?: T
28
- hooks?: Partial<NuxtHooks>
29
- setup?: (this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn>
30
- }
31
-
32
- interface NuxtModule<T extends ModuleOptions = ModuleOptions> {
33
- (this: void, inlineOptions: T, nuxt: Nuxt): Awaitable<void | false | ModuleSetupReturn>
34
- getOptions?: (inlineOptions?: T, nuxt?: Nuxt) => Promise<T>
35
- getMeta?: () => Promise<ModuleMeta>
36
- }
37
-
38
- interface ModuleSetupReturn {
39
- timings?: {
40
- setup?: number
41
- [key: string]: number | undefined
19
+ ```ts twoslash
20
+ import { defineNuxtModule } from '@nuxt/kit'
21
+
22
+ export default defineNuxtModule({
23
+ meta: {
24
+ name: 'my-module',
25
+ configKey: 'myModule'
26
+ },
27
+ defaults: {
28
+ enabled: true
29
+ },
30
+ setup (options) {
31
+ if (options.enabled) {
32
+ console.log('My Nuxt module is enabled!')
33
+ }
42
34
  }
43
- }
44
-
45
- interface ModuleMeta {
46
- name?: string
47
- version?: string
48
- configKey?: string
49
- compatibility?: NuxtCompatibility
50
- [key: string]: unknown
51
- }
35
+ })
52
36
  ```
53
37
 
54
- ### Parameters
55
-
56
- #### `definition`
57
-
58
- **Type**: `ModuleDefinition<T> | NuxtModule<T>`
59
-
60
- **Required**: `true`
61
-
62
- A module definition object or a module function.
63
-
64
- - `meta` (optional)
65
-
66
- **Type**: `ModuleMeta`
67
-
68
- Metadata of the module. It defines the module name, version, config key and compatibility.
69
-
70
- - `defaults` (optional)
71
-
72
- **Type**: `T | ((nuxt: Nuxt) => T)`
73
-
74
- Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument.
75
-
76
- - `schema` (optional)
77
-
78
- **Type**: `T`
79
-
80
- Schema for the module options. If provided, options will be applied to the schema.
38
+ ### Type
81
39
 
82
- - `hooks` (optional)
40
+ ```ts twoslash
41
+ // @errors: 2391
42
+ import type { ModuleDefinition, ModuleOptions, NuxtModule } from '@nuxt/schema'
43
+ // ---cut---
44
+ export function defineNuxtModule<TOptions extends ModuleOptions> (
45
+ definition?: ModuleDefinition<TOptions, Partial<TOptions>, false> | NuxtModule<TOptions, Partial<TOptions>, false>,
46
+ ): NuxtModule<TOptions, TOptions, false>
47
+ ```
83
48
 
84
- **Type**: `Partial<NuxtHooks>`
49
+ ### Parameters
85
50
 
86
- Hooks to be installed for the module. If provided, the module will install the hooks.
51
+ **definition**: A module definition object or a module function. The module definition object should contain the following properties:
87
52
 
88
- - `setup` (optional)
53
+ | Property | Type | Required | Description |
54
+ | ------------------ | -------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- |
55
+ | `meta` | `ModuleMeta` | `false` | Metadata of the module. It defines the module name, version, config key and compatibility. |
56
+ | `defaults` | `T \| ((nuxt: Nuxt) => T)`{lang="ts"} | `false` | Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument. |
57
+ | `schema` | `T` | `false` | Schema for the module options. If provided, options will be applied to the schema. |
58
+ | `hooks` | `Partial<NuxtHooks>`{lang="ts"} | `false` | Hooks to be installed for the module. If provided, the module will install the hooks. |
59
+ | `setup` | `(this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void \| false \| ModuleSetupInstallResult>`{lang="ts"} | `false` | Setup function for the module. If provided, the module will call the setup function. |
89
60
 
90
- **Type**: `(this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable<void | false | ModuleSetupReturn>`
61
+ ### Examples
91
62
 
92
- Setup function for the module. If provided, the module will call the setup function.
63
+ #### Using `configKey` to Make Your Module Configurable
93
64
 
94
- ### Examples
65
+ When defining a Nuxt module, you can set a `configKey` to specify how users should configure the module in their `nuxt.config`.
95
66
 
96
67
  ```ts
97
- // https://github.com/nuxt/starter/tree/module
98
68
  import { defineNuxtModule } from '@nuxt/kit'
99
69
 
100
70
  export default defineNuxtModule({
@@ -103,51 +73,94 @@ export default defineNuxtModule({
103
73
  configKey: 'myModule'
104
74
  },
105
75
  defaults: {
106
- test: 123
76
+ // Module options
77
+ enabled: true
107
78
  },
108
- setup (options, nuxt) {
109
- nuxt.hook('modules:done', () => {
110
- console.log('My module is ready with current test option: ', options.test)
111
- })
79
+ setup (options) {
80
+ if (options.enabled) {
81
+ console.log('My Nuxt module is enabled!')
82
+ }
112
83
  }
113
84
  })
114
85
  ```
115
86
 
116
- ## `installModule`
117
-
118
- Install specified Nuxt module programmatically. This is helpful when your module depends on other modules. You can pass the module options as an object to `inlineOptions` and they will be passed to the module's `setup` function.
119
-
120
- ### Type
87
+ Users can provide options for this module under the corresponding key in `nuxt.config`.
121
88
 
122
89
  ```ts
123
- async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt)
90
+ export default defineNuxtConfig({
91
+ myModule: {
92
+ enabled: false
93
+ }
94
+ })
124
95
  ```
125
96
 
126
- ### Parameters
97
+ #### Defining Module Compatibility Requirements
98
+
99
+ If you're developing a Nuxt module and using APIs that are only supported in specific Nuxt versions, it's highly recommended to include `compatibility.nuxt`.
127
100
 
128
- #### `moduleToInstall`
101
+ ```ts
102
+ export default defineNuxtModule({
103
+ meta: {
104
+ name: '@nuxt/icon',
105
+ configKey: 'icon',
106
+ compatibility: {
107
+ // Required nuxt version in semver format.
108
+ nuxt: '>=3.0.0', // or use '^3.0.0'
109
+ },
110
+ },
111
+ async setup() {
112
+ const resolver = createResolver(import.meta.url)
113
+ // Implement
114
+ },
115
+ })
116
+ ```
129
117
 
130
- **Type**: `string` | `NuxtModule`
118
+ If the user tries to use your module with an incompatible Nuxt version, they will receive a warning in the console.
131
119
 
132
- **Required**: `true`
120
+ ```terminal
121
+ WARN Module @nuxt/icon is disabled due to incompatibility issues:
122
+ - [nuxt] Nuxt version ^3.1.0 is required but currently using 3.0.0
123
+ ```
133
124
 
134
- The module to install. Can be either a string with the module name or a module object itself.
125
+ ## `installModule`
135
126
 
136
- #### `inlineOptions`
127
+ Install specified Nuxt module programmatically. This is helpful when your module depends on other modules. You can pass the module options as an object to `inlineOptions` and they will be passed to the module's `setup` function.
137
128
 
138
- **Type**: `any`
129
+ ### Usage
139
130
 
140
- **Default**: `{}`
131
+ ```ts twoslash
132
+ import { defineNuxtModule, installModule } from '@nuxt/kit'
141
133
 
142
- An object with the module options to be passed to the module's `setup` function.
134
+ export default defineNuxtModule({
135
+ async setup () {
136
+ // will install @nuxtjs/fontaine with Roboto font and Impact fallback
137
+ await installModule('@nuxtjs/fontaine', {
138
+ // module configuration
139
+ fonts: [
140
+ {
141
+ family: 'Roboto',
142
+ fallbacks: ['Impact'],
143
+ fallbackName: 'fallback-a',
144
+ }
145
+ ]
146
+ })
147
+ }
148
+ })
149
+ ```
143
150
 
144
- #### `nuxt`
151
+ ### Type
145
152
 
146
- **Type**: `Nuxt`
153
+ ```ts
154
+ async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt)
155
+ ```
147
156
 
148
- **Default**: `useNuxt()`
157
+ ### Parameters
149
158
 
150
- Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call.
159
+ | Property | Type | Required | Description |
160
+ | ------------------ | -------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- |
161
+ | `moduleToInstall` | `string \| NuxtModule`{lang="ts"} | `true` | The module to install. Can be either a string with the module name or a module object itself. |
162
+ | `inlineOptions` | `any` | `false` | An object with the module options to be passed to the module's `setup` function. |
163
+ | `nuxt` | `Nuxt` | `false` | Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call. |
151
164
 
152
165
  ### Examples
153
166