Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

feat(nuxt): allow useAppConfig with specific key #6776

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion docs/content/2.guide/2.features/10.app-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,28 @@ export default defineAppConfig({
})
```

When adding `theme` to the `app.config`, Nuxt uses Vite or Webpack to bundle the code. We can universally access `theme` in both server and browser using [useAppConfig](/api/composables/use-app-config) composable.
When adding `theme` to the `app.config`, Nuxt uses Vite or Webpack to bundle the code to both Server and client bundles.

In order to access the runtime config value, we can [useAppConfig](/api/composables/use-app-config) composable. Returned value is a reactive object.

```js
const appConfig = useAppConfig()

console.log(appConfig.theme)
```

Or if you need to access a sub-key:

```js
const themeConfig = useAppConfig('theme')

console.log(themeConfig)
```

::alert{type=warning}
Destructuring `appConfig` causes it to loose reactivity. Always use `computed` or provide key to access a sub-key.
pi0 marked this conversation as resolved.
Show resolved Hide resolved
::

<!-- TODO: Document module author for extension -->

### Manually Typing App Config
Expand Down
4 changes: 3 additions & 1 deletion docs/content/3.api/1.composables/use-app-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ Access [app config](/guide/features/app-config):
**Usage:**

```js
// Access whole app config (reactive object)
const appConfig = useAppConfig()

console.log(appConfig)
// Access sub key of app-config (still reactive)
const themeConfig = useAppConfig('theme')
```

::ReadMore{link="/guide/features/app-config"}
7 changes: 5 additions & 2 deletions packages/nuxt/src/app/config.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import type { AppConfig } from '@nuxt/schema'
import { reactive } from 'vue'
import { reactive, computed } from 'vue'
import { useNuxtApp } from './nuxt'
// @ts-ignore
import __appConfig from '#build/app.config.mjs'

// Workaround for vite HMR with virtual modules
export const _getAppConfig = () => __appConfig as AppConfig

export function useAppConfig (): AppConfig {
export function useAppConfig (key?: string): AppConfig {
const nuxtApp = useNuxtApp()
if (!nuxtApp._appConfig) {
nuxtApp._appConfig = reactive(__appConfig) as AppConfig
}
if (key) {
return computed(() => nuxtApp._appConfig[key])
}
return nuxtApp._appConfig
}

Expand Down