fix(kit): fix `addServerImportsDir` implementation (#24000)

This commit is contained in:
Daniel Roe 2023-10-31 14:16:01 +01:00 committed by GitHub
parent 69ddcc968d
commit ebb5767b9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 7 deletions

View File

@ -358,3 +358,40 @@ export default defineNuxtModule({
}
})
```
## `addServerImportsDir`
Add a directory to be scanned for auto-imports by Nitro.
### Type
```ts
function function addServerImportsDir (dirs: string | string[], opts: { prepend?: boolean }): void
```
### Parameters
#### `dirs`
**Type**: `string | string[]`
**Required**: `true`
A directory or an array of directories to register to be scanned by Nitro
### Examples
```ts
import { defineNuxtModule, addServerImportsDir } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule',
},
setup(options) {
const resolver = createResolver(import.meta.url)
addServerImportsDir(resolver.resolve('./runtime/server/utils'))
}
})
```

View File

@ -99,15 +99,14 @@ export function addServerImports (imports: Import[]) {
}
/**
* Add directories to be scanned by Nitro
* Add directories to be scanned for auto-imports by Nitro
*/
export function addServerImportsDir (dirs: string | string[], opts: { prepend?: boolean } = {}) {
const nuxt = useNuxt()
const _dirs = Array.isArray(dirs) ? dirs : [dirs]
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)
}
config.imports = config.imports || {}
config.imports.dirs = config.imports.dirs || []
config.imports.dirs[opts.prepend ? 'unshift' : 'push'](..._dirs)
})
}

View File

@ -21,6 +21,6 @@ export default defineNuxtModule({
name: 'someUtils'
}])
addServerImportsDir(resolver.resolve('./runtime/server'))
addServerImportsDir(resolver.resolve('./runtime/server/utils'))
}
})