Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nuxt): auto-register modules in ~/modules #19394

Merged
merged 19 commits into from
Mar 3, 2023
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions docs/2.guide/2.directory-structure/1.modules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
navigation.icon: IconDirectory
title: 'modules'
head.title: 'modules/'
description: Use the modules/ directory to automatically register local modules within your application.
---

# Modules Directory

Nuxt scans the `modules/` directory and loads them before starting. It is a good place to place any local modules you develop while building your application.

The auto-registered files patterns are:
- `modules/*/index.ts`
- `modules/*.ts`

You don't need to add those local modules to your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) separately.

::code-group
```ts [modules/hello/index.ts]
// `nuxt/kit` is a helper subpath import you can use when defining local modules
// that means you do not need to add `@nuxt/kit` to your project's dependencies
import { createResolver, defineNuxtModule, addServerHandler } from 'nuxt/kit'

export default defineNuxtModule({
meta: {
name: 'hello'
},
setup () {
const { resolve } = createResolver(import.meta.url)

// Add an API route
addServerHandler({
route: '/api/hello',
handler: resolve('./runtime/api-route')
})
}
})
```
```ts [modules/hello/runtime/api-route.ts]
export default defineEventHandler(() => {
return { hello: 'world' }
}
```
::

When starting Nuxt, the `hello` module will be registered and the `/api/hello` route will be available.

:ReadMore{link="/docs/guide/going-further/modules"}
30 changes: 24 additions & 6 deletions packages/nuxt/src/core/nuxt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { join, normalize, resolve } from 'pathe'
import { join, normalize, relative, resolve } from 'pathe'
import { createHooks, createDebugger } from 'hookable'
import type { LoadNuxtOptions } from '@nuxt/kit'
import { loadNuxtConfig, nuxtCtx, installModule, addComponent, addVitePlugin, addWebpackPlugin, tryResolveModule, addPlugin } from '@nuxt/kit'
import { resolveFiles, loadNuxtConfig, nuxtCtx, installModule, addComponent, addVitePlugin, addWebpackPlugin, tryResolveModule, addPlugin } from '@nuxt/kit'

import escapeRE from 'escape-string-regexp'
import fse from 'fs-extra'
Expand Down Expand Up @@ -122,10 +122,28 @@ async function initNuxt (nuxt: Nuxt) {

// Init user modules
await nuxt.callHook('modules:before')
const modulesToInstall = [
...nuxt.options.modules,
...nuxt.options._modules
]
const modulesToInstall = []

const watchedPaths = new Set<string>()

// Automatically register user modules
for (const config of nuxt.options._layers.map(layer => layer.config).reverse()) {
const layerModules = await resolveFiles(config.srcDir, [
`${config.dir?.modules || 'modules'}/*{${nuxt.options.extensions.join(',')}}`,
`${config.dir?.modules || 'modules'}/*/index{${nuxt.options.extensions.join(',')}}`
])
for (const mod of layerModules) {
modulesToInstall.push(mod)
pi0 marked this conversation as resolved.
Show resolved Hide resolved
watchedPaths.add(relative(config.srcDir, mod))
}
}

// Register user and then ad-hoc modules
modulesToInstall.push(...nuxt.options.modules, ...nuxt.options._modules)

nuxt.hooks.hookOnce('builder:watch', (event, path) => {
if (watchedPaths.has(path)) { nuxt.callHook('restart', { hard: true }) }
})

// Add <NuxtWelcome>
addComponent({
Expand Down
5 changes: 5 additions & 0 deletions packages/schema/src/config/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,11 @@ export default defineUntypedSchema({
*/
middleware: 'middleware',

/**
* The modules directory, each file in which will be auto-registered as a Nuxt module.
*/
modules: 'modules',

/**
* The directory which will be processed to auto-generate your application page routes.
*/
Expand Down
7 changes: 7 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ describe('route rules', () => {
})
})

describe('modules', () => {
it('should auto-register modules in ~/modules', async () => {
const result = await $fetch('/auto-registered-module')
expect(result).toEqual('handler added by auto-registered module')
})
})

describe('pages', () => {
it('render index', async () => {
const html = await $fetch('/')
Expand Down
15 changes: 15 additions & 0 deletions test/fixtures/basic/modules/auto-registered/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createResolver, defineNuxtModule, addServerHandler } from 'nuxt/kit'

export default defineNuxtModule({
meta: {
name: 'auto-registered-module'
},
setup () {
const resolver = createResolver(import.meta.url)

addServerHandler({
handler: resolver.resolve('./runtime/handler'),
route: '/auto-registered-module'
})
}
})
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default defineEventHandler(() => 'handler added by auto-registered module')
9 changes: 5 additions & 4 deletions test/fixtures/basic/modules/example.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { fileURLToPath } from 'node:url'
import { defineNuxtModule, addPlugin, useNuxt } from '@nuxt/kit'
import { defineNuxtModule, createResolver, addPlugin, useNuxt } from 'nuxt/kit'

export default defineNuxtModule({
defaults: {
Expand All @@ -11,11 +10,13 @@ export default defineNuxtModule({
configKey: 'sampleModule'
},
setup () {
addPlugin(fileURLToPath(new URL('./runtime/plugin', import.meta.url)))
const resolver = createResolver(import.meta.url)

addPlugin(resolver.resolve('./runtime/plugin'))
useNuxt().hook('app:resolve', (app) => {
app.middleware.push({
name: 'unctx-test',
path: fileURLToPath(new URL('./runtime/middleware', import.meta.url)),
path: resolver.resolve('./runtime/middleware'),
global: true
})
})
Expand Down