feat(kit): add addServerImports and addServerImportsDir (#23288)

This commit is contained in:
Julien Huang 2023-09-28 12:08:02 +02:00 committed by GitHub
parent 1b34386707
commit 2b273fa8e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 67 additions and 1 deletions

View File

@ -1,4 +1,5 @@
import type { Nitro, NitroDevEventHandler, NitroEventHandler } from 'nitropack'
import type { Import } from 'unimport'
import { normalize } from 'pathe'
import { useNuxt } from './context'
@ -82,3 +83,33 @@ export function useNitro (): Nitro {
}
return (nuxt as any)._nitro
}
/**
* Add server imports to be auto-imported by Nitro
*/
export function addServerImports (imports: Import[]) {
const nuxt = useNuxt()
nuxt.hook('nitro:config', (config) => {
config.imports = config.imports || {}
config.imports.autoImport = true
if (Array.isArray(config.imports.imports)) {
config.imports.imports = [...config.imports.imports, ...imports]
} else {
config.imports.imports = [config.imports.imports, ...imports]
}
})
}
/**
* Add directories to be scanned by Nitro
*/
export function addServerImportsDir (dirs: string | string[], opts: { prepend?: boolean } = {}) {
const nuxt = useNuxt()
nuxt.hook('nitro:config', (config) => {
config.scanDirs = config.scanDirs || []
for (const dir of (Array.isArray(dirs) ? dirs : [dirs])) {
config.scanDirs[opts.prepend ? 'unshift' : 'push'](dir)
}
})
}

View File

@ -41,6 +41,17 @@ describe('server api', () => {
expect(await $fetch('/api/counter')).toEqual({ count: 2 })
expect(await $fetch('/api/counter')).toEqual({ count: 3 })
})
it('should auto-import', async () => {
const res = await $fetch('/api/auto-imports')
expect(res).toMatchInlineSnapshot(`
{
"autoImported": "utils",
"fromServerDir": "test-utils",
"thisIs": "serverAutoImported",
}
`)
})
})
describe('route rules', () => {

View File

@ -1,4 +1,4 @@
import { addServerHandler, createResolver, defineNuxtModule } from 'nuxt/kit'
import { addServerHandler, addServerImports, addServerImportsDir, createResolver, defineNuxtModule } from 'nuxt/kit'
export default defineNuxtModule({
meta: {
@ -11,5 +11,16 @@ export default defineNuxtModule({
handler: resolver.resolve('./runtime/handler'),
route: '/auto-registered-module'
})
addServerImports([{
from: resolver.resolve('./runtime/some-server-import'),
name: 'serverAutoImported',
as: 'autoimportedFunction'
}, {
from: resolver.resolve('./runtime/some-server-import'),
name: 'someUtils'
}])
addServerImportsDir(resolver.resolve('./runtime/server'))
}
})

View File

@ -0,0 +1 @@
export const testUtils = 'test-utils'

View File

@ -0,0 +1,5 @@
export function serverAutoImported () {
return 'serverAutoImported'
}
export const someUtils = 'utils'

View File

@ -0,0 +1,7 @@
export default defineEventHandler(() => {
return {
thisIs: autoimportedFunction(),
autoImported: someUtils,
fromServerDir: testUtils
}
})