fix(nuxt): provide fallback values for undefined runtime config (#18586)

This commit is contained in:
Daniel Roe 2023-01-28 07:18:04 -08:00 committed by GitHub
parent 6c4cf5cdcb
commit b8f6243621
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 8 deletions

View File

@ -423,14 +423,17 @@ export default defineUntypedSchema({
* @type {typeof import('../src/types/config').RuntimeConfig}
*/
runtimeConfig: {
$resolve: async (val: RuntimeConfig, get) => defu(val, {
public: {},
app: {
baseURL: (await get('app')).baseURL,
buildAssetsDir: (await get('app')).buildAssetsDir,
cdnURL: (await get('app')).cdnURL,
}
})
$resolve: async (val: RuntimeConfig, get) => {
provideFallbackValues(val)
return defu(val, {
public: {},
app: {
baseURL: (await get('app')).baseURL,
buildAssetsDir: (await get('app')).buildAssetsDir,
cdnURL: (await get('app')).cdnURL,
}
})
}
},
/**
@ -445,3 +448,13 @@ export default defineUntypedSchema({
$schema: {}
})
function provideFallbackValues (obj: Record<string, any>) {
for (const key in obj) {
if (typeof obj[key] === 'undefined' || obj[key] === null) {
obj[key] = ''
} else if (typeof obj[key] === 'object') {
provideFallbackValues(obj[key])
}
}
}

View File

@ -52,6 +52,7 @@ describe('pages', () => {
expect(html).toContain('Hello Nuxt 3!')
// should inject runtime config
expect(html).toContain('RuntimeConfig | testConfig: 123')
expect(html).toContain('needsFallback:')
// composables auto import
expect(html).toContain('Composable | foo: auto imported from ~/components/foo.ts')
expect(html).toContain('Composable | bar: auto imported from ~/components/useBar.ts')

View File

@ -51,6 +51,7 @@ export default defineNuxtConfig({
runtimeConfig: {
privateConfig: 'secret_key',
public: {
needsFallback: undefined,
testConfig: 123
}
},