fix(nuxt): provide typescript aliases for core packages (#26158)

This commit is contained in:
Daniel Roe 2024-03-08 22:58:37 +00:00 committed by GitHub
parent f0fd15bcf7
commit dd1cdbc052
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 32 additions and 19 deletions

View File

@ -9,8 +9,7 @@ import { joinURL, withQuery } from 'ufo'
import type { FetchResponse } from 'ofetch' import type { FetchResponse } from 'ofetch'
import { join } from 'pathe' import { join } from 'pathe'
// eslint-disable-next-line import/no-restricted-paths import type { NuxtIslandResponse } from '../types'
import type { NuxtIslandResponse } from '../../core/runtime/nitro/renderer'
import { useNuxtApp, useRuntimeConfig } from '../nuxt' import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import { prerenderRoutes, useRequestEvent } from '../composables/ssr' import { prerenderRoutes, useRequestEvent } from '../composables/ssr'
import { getFragmentHTML } from './utils' import { getFragmentHTML } from './utils'

View File

@ -11,8 +11,7 @@ import type { AppConfig, AppConfigInput, RuntimeConfig } from 'nuxt/schema'
import type { RenderResponse } from 'nitropack' import type { RenderResponse } from 'nitropack'
import type { MergeHead, VueHeadClient } from '@unhead/vue' import type { MergeHead, VueHeadClient } from '@unhead/vue'
// eslint-disable-next-line import/no-restricted-paths import type { NuxtIslandContext } from '../app/types'
import type { NuxtIslandContext } from '../core/runtime/nitro/renderer'
import type { RouteMiddleware } from '../app/composables/router' import type { RouteMiddleware } from '../app/composables/router'
import type { NuxtError } from '../app/composables/error' import type { NuxtError } from '../app/composables/error'
import type { AsyncDataRequestStatus } from '../app/composables/asyncData' import type { AsyncDataRequestStatus } from '../app/composables/asyncData'

View File

@ -4,3 +4,6 @@ export type { PageMeta } from '../pages/runtime/index'
export interface NuxtAppLiterals { export interface NuxtAppLiterals {
[key: string]: string [key: string]: string
} }
// eslint-disable-next-line import/no-restricted-paths
export type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from '../core/runtime/nitro/renderer'

View File

@ -1,8 +1,9 @@
import { join, normalize, relative, resolve } from 'pathe' import { dirname, join, normalize, relative, resolve } from 'pathe'
import { createDebugger, createHooks } from 'hookable' import { createDebugger, createHooks } from 'hookable'
import type { LoadNuxtOptions } from '@nuxt/kit' import type { LoadNuxtOptions } from '@nuxt/kit'
import { addBuildPlugin, addComponent, addPlugin, addRouteMiddleware, addVitePlugin, addWebpackPlugin, installModule, loadNuxtConfig, logger, nuxtCtx, resolveAlias, resolveFiles, resolvePath, tryResolveModule, useNitro } from '@nuxt/kit' import { addBuildPlugin, addComponent, addPlugin, addRouteMiddleware, addVitePlugin, addWebpackPlugin, installModule, loadNuxtConfig, logger, nuxtCtx, resolveAlias, resolveFiles, resolvePath, tryResolveModule, useNitro } from '@nuxt/kit'
import type { Nuxt, NuxtHooks, NuxtOptions } from 'nuxt/schema' import type { Nuxt, NuxtHooks, NuxtOptions } from 'nuxt/schema'
import { resolvePackageJSON } from 'pkg-types'
import escapeRE from 'escape-string-regexp' import escapeRE from 'escape-string-regexp'
import fse from 'fs-extra' import fse from 'fs-extra'
@ -61,6 +62,17 @@ async function initNuxt (nuxt: Nuxt) {
nuxtCtx.set(nuxt) nuxtCtx.set(nuxt)
nuxt.hook('close', () => nuxtCtx.unset()) nuxt.hook('close', () => nuxtCtx.unset())
const coreTypePackages = ['nitropack', 'defu', 'h3', '@unhead/vue', 'vue', 'vue-router', '@nuxt/schema']
const paths = Object.fromEntries(await Promise.all(coreTypePackages.map(async pkg => {
const path = await resolvePath(pkg).then(r => resolvePackageJSON(r))
return [pkg, [dirname(path)]]
})))
// Set nitro resolutions for types that might be obscured with shamefully-hoist=false
nuxt.options.nitro.typescript = defu(nuxt.options.nitro.typescript, {
tsConfig: { compilerOptions: { paths } }
})
// Add nuxt types // Add nuxt types
nuxt.hook('prepare:types', (opts) => { nuxt.hook('prepare:types', (opts) => {
opts.references.push({ types: 'nuxt' }) opts.references.push({ types: 'nuxt' })
@ -73,6 +85,9 @@ async function initNuxt (nuxt: Nuxt) {
opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/schema.d.ts') }) opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/schema.d.ts') })
opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/app.config.d.ts') }) opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/app.config.d.ts') })
// Set Nuxt resolutions for types that might be obscured with shamefully-hoist=false
opts.tsConfig.compilerOptions = defu(opts.tsConfig.compilerOptions, { paths })
for (const layer of nuxt.options._layers) { for (const layer of nuxt.options._layers) {
const declaration = join(layer.cwd, 'index.d.ts') const declaration = join(layer.cwd, 'index.d.ts')
if (fse.existsSync(declaration)) { if (fse.existsSync(declaration)) {

View File

@ -8,7 +8,6 @@ import { hash } from 'ohash'
import { camelCase } from 'scule' import { camelCase } from 'scule'
import { filename } from 'pathe/utils' import { filename } from 'pathe/utils'
import type { NuxtTemplate } from 'nuxt/schema' import type { NuxtTemplate } from 'nuxt/schema'
import { tryResolveModule } from '@nuxt/kit'
import { annotatePlugins, checkForCircularDependencies } from './app' import { annotatePlugins, checkForCircularDependencies } from './app'
@ -223,14 +222,13 @@ export const middlewareTemplate: NuxtTemplate = {
export const nitroSchemaTemplate: NuxtTemplate = { export const nitroSchemaTemplate: NuxtTemplate = {
filename: 'types/nitro-nuxt.d.ts', filename: 'types/nitro-nuxt.d.ts',
async getContents ({ nuxt }) { getContents () {
const localH3 = await tryResolveModule('h3', nuxt.options.modulesDir) || 'h3'
return /* typescript */` return /* typescript */`
/// <reference path="./schema.d.ts" /> /// <reference path="./schema.d.ts" />
import type { RuntimeConfig } from 'nuxt/schema' import type { RuntimeConfig } from 'nuxt/schema'
import type { H3Event } from '${localH3}' import type { H3Event } from 'h3'
import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from 'nuxt/dist/core/runtime/nitro/renderer' import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from 'nuxt/app'
declare module 'nitropack' { declare module 'nitropack' {
interface NitroRuntimeConfigApp { interface NitroRuntimeConfigApp {
@ -264,11 +262,10 @@ export const useRuntimeConfig = () => window?.__NUXT__?.config || {}
export const appConfigDeclarationTemplate: NuxtTemplate = { export const appConfigDeclarationTemplate: NuxtTemplate = {
filename: 'types/app.config.d.ts', filename: 'types/app.config.d.ts',
async getContents ({ app, nuxt }) { getContents ({ app, nuxt }) {
const localDefu = await tryResolveModule('defu', nuxt.options.modulesDir) || 'defu'
return ` return `
import type { CustomAppConfig } from 'nuxt/schema' import type { CustomAppConfig } from 'nuxt/schema'
import type { Defu } from '${localDefu}' import type { Defu } from 'defu'
${app.configs.map((id: string, index: number) => `import ${`cfg${index}`} from ${JSON.stringify(id.replace(/(?<=\w)\.\w+$/g, ''))}`).join('\n')} ${app.configs.map((id: string, index: number) => `import ${`cfg${index}`} from ${JSON.stringify(id.replace(/(?<=\w)\.\w+$/g, ''))}`).join('\n')}
declare const inlineConfig = ${JSON.stringify(nuxt.options.appConfig, null, 2)} declare const inlineConfig = ${JSON.stringify(nuxt.options.appConfig, null, 2)}
@ -302,11 +299,10 @@ declare module '@nuxt/schema' {
export const appConfigTemplate: NuxtTemplate = { export const appConfigTemplate: NuxtTemplate = {
filename: 'app.config.mjs', filename: 'app.config.mjs',
write: true, write: true,
async getContents ({ app, nuxt }) { getContents ({ app, nuxt }) {
const localDefu = await tryResolveModule('defu', nuxt.options.modulesDir) || 'defu'
return ` return `
import { updateAppConfig } from '#app/config' import { updateAppConfig } from '#app/config'
import { defuFn } from '${localDefu}' import { defuFn } from 'defu'
const inlineConfig = ${JSON.stringify(nuxt.options.appConfig, null, 2)} const inlineConfig = ${JSON.stringify(nuxt.options.appConfig, null, 2)}

View File

@ -4,7 +4,7 @@ export * from './dist/index.js'
import type { DefineNuxtConfig } from 'nuxt/config' import type { DefineNuxtConfig } from 'nuxt/config'
import type { RuntimeConfig, SchemaDefinition } from 'nuxt/schema' import type { RuntimeConfig, SchemaDefinition } from 'nuxt/schema'
import type { H3Event } from 'h3' import type { H3Event } from 'h3'
import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from './dist/core/runtime/nitro/renderer.js' import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from './dist/app/types.js'
declare global { declare global {
const defineNuxtConfig: DefineNuxtConfig const defineNuxtConfig: DefineNuxtConfig

View File

@ -4,7 +4,7 @@ export * from './dist/index'
import type { DefineNuxtConfig } from 'nuxt/config' import type { DefineNuxtConfig } from 'nuxt/config'
import type { RuntimeConfig, SchemaDefinition } from 'nuxt/schema' import type { RuntimeConfig, SchemaDefinition } from 'nuxt/schema'
import type { H3Event } from 'h3' import type { H3Event } from 'h3'
import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from './dist/core/runtime/nitro/renderer' import type { NuxtIslandContext, NuxtIslandResponse, NuxtRenderHTMLContext } from './dist/app/types'
declare global { declare global {
const defineNuxtConfig: DefineNuxtConfig const defineNuxtConfig: DefineNuxtConfig

View File

@ -7,9 +7,10 @@ import { join, normalize } from 'pathe'
import { $fetch, createPage, fetch, isDev, setup, startServer, url, useTestContext } from '@nuxt/test-utils/e2e' import { $fetch, createPage, fetch, isDev, setup, startServer, url, useTestContext } from '@nuxt/test-utils/e2e'
import { $fetchComponent } from '@nuxt/test-utils/experimental' import { $fetchComponent } from '@nuxt/test-utils/experimental'
import type { NuxtIslandResponse } from '../packages/nuxt/src/core/runtime/nitro/renderer'
import { expectNoClientErrors, expectWithPolling, gotoPath, isRenderingJson, parseData, parsePayload, renderPage } from './utils' import { expectNoClientErrors, expectWithPolling, gotoPath, isRenderingJson, parseData, parsePayload, renderPage } from './utils'
import type { NuxtIslandResponse } from '#app'
const isWebpack = process.env.TEST_BUILDER === 'webpack' const isWebpack = process.env.TEST_BUILDER === 'webpack'
const isTestingAppManifest = process.env.TEST_MANIFEST !== 'manifest-off' const isTestingAppManifest = process.env.TEST_MANIFEST !== 'manifest-off'