fix(kit): improve types for options in addTemplate (#25109)

This commit is contained in:
Inesh Bose 2024-01-12 10:47:23 +00:00 committed by GitHub
parent 22800704f5
commit 406b204640
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 29 additions and 41 deletions

View File

@ -9,7 +9,7 @@ import { toArray } from '../utils'
/** @deprecated */
// TODO: Remove support for compiling ejs templates in v4
export async function compileTemplate (template: NuxtTemplate, ctx: any) {
export async function compileTemplate <T>(template: NuxtTemplate<T>, ctx: any) {
const data = { ...ctx, options: template.options }
if (template.src) {
try {

View File

@ -16,7 +16,7 @@ import { resolveNuxtModule } from './resolve'
/**
* Renders given template using lodash template during build into the project buildDir
*/
export function addTemplate (_template: NuxtTemplate<any> | string) {
export function addTemplate <T>(_template: NuxtTemplate<T> | string) {
const nuxt = useNuxt()
// Normalize template
@ -36,7 +36,7 @@ export function addTemplate (_template: NuxtTemplate<any> | string) {
* Renders given types using lodash template during build into the project buildDir
* and register them as types.
*/
export function addTypeTemplate (_template: NuxtTypeTemplate<any>) {
export function addTypeTemplate <T>(_template: NuxtTypeTemplate<T>) {
const nuxt = useNuxt()
const template = addTemplate(_template)
@ -56,7 +56,7 @@ export function addTypeTemplate (_template: NuxtTypeTemplate<any>) {
/**
* Normalize a nuxt template object
*/
export function normalizeTemplate (template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any> {
export function normalizeTemplate <T>(template: NuxtTemplate<T> | string): ResolvedNuxtTemplate<T> {
if (!template) {
throw new Error('Invalid template: ' + JSON.stringify(template))
}
@ -99,7 +99,7 @@ export function normalizeTemplate (template: NuxtTemplate<any> | string): Resolv
template.dst = resolve(nuxt.options.buildDir, template.filename)
}
return template as ResolvedNuxtTemplate<any>
return template as ResolvedNuxtTemplate<T>
}
/**

View File

@ -1,15 +1,6 @@
import { isAbsolute, relative } from 'pathe'
import { genDynamicImport } from 'knitwork'
import type { Component, Nuxt, NuxtApp, NuxtPluginTemplate, NuxtTemplate } from 'nuxt/schema'
interface ComponentsTemplateContext {
app: NuxtApp
nuxt: Nuxt
options: {
getComponents: (mode?: 'client' | 'server' | 'all') => Component[]
mode?: 'client' | 'server'
}
}
import type { NuxtPluginTemplate, NuxtTemplate } from 'nuxt/schema'
type ImportMagicCommentsOptions = {
chunkName: string
@ -70,14 +61,14 @@ export default defineNuxtPlugin({
}
}
export const componentNamesTemplate: NuxtTemplate<ComponentsTemplateContext> = {
export const componentNamesTemplate: NuxtTemplate = {
filename: 'component-names.mjs',
getContents ({ app }) {
return `export const componentNames = ${JSON.stringify(app.components.filter(c => !c.island).map(c => c.pascalName))}`
}
}
export const componentsIslandsTemplate: NuxtTemplate<ComponentsTemplateContext> = {
export const componentsIslandsTemplate: NuxtTemplate = {
// components.islands.mjs'
getContents ({ app }) {
const components = app.components
@ -102,7 +93,7 @@ export const componentsIslandsTemplate: NuxtTemplate<ComponentsTemplateContext>
}
}
export const componentsTypeTemplate: NuxtTemplate<ComponentsTemplateContext> = {
export const componentsTypeTemplate: NuxtTemplate = {
filename: 'components.d.ts',
getContents: ({ app, nuxt }) => {
const buildDir = nuxt.options.buildDir

View File

@ -36,7 +36,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?:
// Compile templates into vfs
// TODO: remove utils in v4
const templateContext = { utils: templateUtils, nuxt, app }
const filteredTemplates = (app.templates as Array<ReturnType<typeof normalizeTemplate>>)
const filteredTemplates = (app.templates as Array<ResolvedNuxtTemplate<any>>)
.filter(template => !options.filter || options.filter(template))
const writes: Array<() => void> = []

View File

@ -7,14 +7,9 @@ import escapeRE from 'escape-string-regexp'
import { hash } from 'ohash'
import { camelCase } from 'scule'
import { filename } from 'pathe/utils'
import type { Nuxt, NuxtApp, NuxtTemplate } from 'nuxt/schema'
import type { NuxtTemplate } from 'nuxt/schema'
import { annotatePlugins, checkForCircularDependencies } from './app'
interface TemplateContext {
nuxt: Nuxt
app: NuxtApp
}
export const vueShim: NuxtTemplate = {
filename: 'types/vue-shim.d.ts',
getContents: ({ nuxt }) => {
@ -33,34 +28,34 @@ export const vueShim: NuxtTemplate = {
}
// TODO: Use an alias
export const appComponentTemplate: NuxtTemplate<TemplateContext> = {
export const appComponentTemplate: NuxtTemplate = {
filename: 'app-component.mjs',
getContents: ctx => genExport(ctx.app.mainComponent!, ['default'])
}
// TODO: Use an alias
export const rootComponentTemplate: NuxtTemplate<TemplateContext> = {
export const rootComponentTemplate: NuxtTemplate = {
filename: 'root-component.mjs',
// TODO: fix upstream in vite - this ensures that vite generates a module graph for islands
// but should not be necessary (and has a warmup performance cost). See https://github.com/nuxt/nuxt/pull/24584.
getContents: ctx => (ctx.nuxt.options.dev ? "import '#build/components.islands.mjs';\n" : '') + genExport(ctx.app.rootComponent!, ['default'])
}
// TODO: Use an alias
export const errorComponentTemplate: NuxtTemplate<TemplateContext> = {
export const errorComponentTemplate: NuxtTemplate = {
filename: 'error-component.mjs',
getContents: ctx => genExport(ctx.app.errorComponent!, ['default'])
}
// TODO: Use an alias
export const testComponentWrapperTemplate = {
export const testComponentWrapperTemplate: NuxtTemplate = {
filename: 'test-component-wrapper.mjs',
getContents: (ctx: TemplateContext) => genExport(resolve(ctx.nuxt.options.appDir, 'components/test-component-wrapper'), ['default'])
getContents: (ctx) => genExport(resolve(ctx.nuxt.options.appDir, 'components/test-component-wrapper'), ['default'])
}
export const cssTemplate: NuxtTemplate<TemplateContext> = {
export const cssTemplate: NuxtTemplate = {
filename: 'css.mjs',
getContents: ctx => ctx.nuxt.options.css.map(i => genImport(i)).join('\n')
}
export const clientPluginTemplate: NuxtTemplate<TemplateContext> = {
export const clientPluginTemplate: NuxtTemplate = {
filename: 'plugins/client.mjs',
async getContents (ctx) {
const clientPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server'))
@ -80,7 +75,7 @@ export const clientPluginTemplate: NuxtTemplate<TemplateContext> = {
}
}
export const serverPluginTemplate: NuxtTemplate<TemplateContext> = {
export const serverPluginTemplate: NuxtTemplate = {
filename: 'plugins/server.mjs',
async getContents (ctx) {
const serverPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'client'))
@ -100,7 +95,7 @@ export const serverPluginTemplate: NuxtTemplate<TemplateContext> = {
}
}
export const pluginsDeclaration: NuxtTemplate<TemplateContext> = {
export const pluginsDeclaration: NuxtTemplate = {
filename: 'types/plugins.d.ts',
getContents: async (ctx) => {
const EXTENSION_RE = new RegExp(`(?<=\\w)(${ctx.nuxt.options.extensions.map(e => escapeRE(e)).join('|')})$`, 'g')
@ -144,7 +139,7 @@ export { }
}
const adHocModules = ['router', 'pages', 'imports', 'meta', 'components', 'nuxt-config-schema']
export const schemaTemplate: NuxtTemplate<TemplateContext> = {
export const schemaTemplate: NuxtTemplate = {
filename: 'types/schema.d.ts',
getContents: async ({ nuxt }) => {
const moduleInfo = nuxt.options._installedModules.map(m => ({
@ -197,7 +192,7 @@ export const schemaTemplate: NuxtTemplate<TemplateContext> = {
}
// Add layouts template
export const layoutTemplate: NuxtTemplate<TemplateContext> = {
export const layoutTemplate: NuxtTemplate = {
filename: 'layouts.mjs',
getContents ({ app }) {
const layoutsObject = genObjectFromRawEntries(Object.values(app.layouts).map(({ name, file }) => {
@ -210,7 +205,7 @@ export const layoutTemplate: NuxtTemplate<TemplateContext> = {
}
// Add middleware template
export const middlewareTemplate: NuxtTemplate<TemplateContext> = {
export const middlewareTemplate: NuxtTemplate = {
filename: 'middleware.mjs',
getContents ({ app }) {
const globalMiddleware = app.middleware.filter(mw => mw.global)
@ -370,9 +365,9 @@ export const dollarFetchTemplate: NuxtTemplate = {
}
// Allow direct access to specific exposed nuxt.config
export const nuxtConfigTemplate = {
export const nuxtConfigTemplate: NuxtTemplate = {
filename: 'nuxt.config.mjs',
getContents: (ctx: TemplateContext) => {
getContents: (ctx) => {
const fetchDefaults = {
...ctx.nuxt.options.experimental.defaults.useFetch,
baseURL: undefined,

View File

@ -366,6 +366,7 @@ export default defineNuxtModule({
addTemplate({
filename: 'routes.mjs',
getContents ({ app }) {
if (!app.pages) return 'export default []'
const { routes, imports } = normalizeRoutes(app.pages)
return [...imports, `export default ${routes}`].join('\n')
}

View File

@ -36,7 +36,7 @@ export interface NuxtTemplate<Options = TemplateDefaultOptions> {
/** The resolved path to the source file to be template */
src?: string
/** Provided compile option instead of src */
getContents?: (data: Options) => string | Promise<string>
getContents?: (data: { nuxt: Nuxt, app: NuxtApp, options: Options }) => string | Promise<string>
/** Write to filesystem */
write?: boolean
}
@ -46,7 +46,8 @@ export interface ResolvedNuxtTemplate<Options = TemplateDefaultOptions> extends
dst: string
}
export interface NuxtTypeTemplate<Options = TemplateDefaultOptions> extends Omit<NuxtTemplate<Options>, 'write'> {
export interface NuxtTypeTemplate<Options = TemplateDefaultOptions> extends Omit<NuxtTemplate<Options>, 'write' | 'filename'> {
filename: `${string}.d.ts`
write?: true
}