Nuxt/docs/2.guide/1.concepts/1.auto-imports.md

121 lines
4.7 KiB
Markdown
Raw Permalink Normal View History

---
description: "Nuxt auto-imports helper functions, composables and Vue APIs."
---
# Auto imports
Nuxt auto-imports helper functions, composables and Vue APIs to use across your application without explicitly importing them. Based on the directory structure, every Nuxt application can also use auto-imports for its own components, composables and plugins. Components, composables or plugins can use these functions.
Contrary to a classic global declaration, Nuxt preserves typings and IDEs completions and hints, and only includes what is actually used in your production code.
::alert{type=info icon=💡}
In the documentation, every function that is not explicitly imported is auto-imported by Nuxt and can be used as-is in your code.
You can find a reference for auto-imported [composables](/docs/api/composables/use-async-data) and [utilities](/docs/api/utils/dollarfetch) in the API section.
::
::alert{type=info}
In the [server directory](/docs/guide/directory-structure/server), we auto import exported functions and variables from `server/utils/`.
::
## Built-in Auto-imports
### Nuxt Auto-imports
Nuxt auto-imports functions and composables to perform [data fetching](/docs/getting-started/data-fetching), get access to the [app context](/docs/api/composables/use-nuxt-app) and [runtime config](/docs/guide/going-further/runtime-config), manage [state](/docs/getting-started/state-management) or define components and plugins.
```vue
<script setup>
/* useAsyncData() and $fetch() are auto-imported */
const { data, refresh, pending } = await useAsyncData('/api/hello', () => $fetch('/api/hello'))
</script>
```
### Vue Auto-imports
Vue 3 exposes Reactivity APIs like `ref` or `computed`, as well as lifecycle hooks and helpers that are auto-imported by Nuxt.
```vue
<script setup>
/* ref() and computed() are auto-imported */
const count = ref(1)
const double = computed(() => count.value * 2)
</script>
```
### Using Vue and Nuxt composables
<!-- TODO: move to separate page with https://github.com/nuxt/nuxt/issues/14723 and add more information -->
When you are using the built-in composition API composables provided by Vue and Nuxt, be aware that many of them rely on being called in the right _context_.
During a component lifecycle, Vue tracks the temporary instance of the current component (and similarly, Nuxt tracks a temporary instance of `nuxtApp`) via a global variable, and then unsets it in same tick. This is essential when server rendering, both to avoid cross-request state pollution (leaking a shared reference between two users) and to avoid leakage between different components.
That means that (with very few exceptions) you cannot use them outside a Nuxt plugin, Nuxt route middleware or Vue setup function. On top of that, you must use them synchronously - that is, you cannot use `await` before calling a composable, except within `<script setup>` blocks, in `defineNuxtPlugin` or in `defineNuxtRouteMiddleware`, where we perform a transform to keep the synchronous context even after the `await`.
If you get an error message like `Nuxt instance is unavailable` then it probably means you are calling a Nuxt composable in the wrong place in the Vue or Nuxt lifecycle.
See the full explanation in this [comment](https://github.com/nuxt/framework/issues/5740#issuecomment-1229197529).
::NeedContribution
::
#### Example
**Example:** Breaking code:
```ts [composables/example.ts]
// trying to access runtime config outside a composable
const config = useRuntimeConfig()
export const useMyComposable = () => {
// accessing runtime config here
}
```
**Example:** Fixing the error:
```ts [composables/example.ts]
export const useMyComposable = () => {
// Because your composable is called in the right place in the lifecycle,
// useRuntimeConfig will also work
const config = useRuntimeConfig()
// ...
}
```
## Directory-based Auto-imports
Nuxt directly auto-imports files created in defined directories:
- `components/` for [Vue components](/docs/guide/directory-structure/components).
- `composables/` for [Vue composables](/docs/guide/directory-structure/composables).
- `utils/` for helper functions and other utilities.
## Explicit Imports
Nuxt exposes every auto-import with the `#imports` alias that can be used to make the import explicit if needed:
```vue
<script setup>
import { ref, computed } from '#imports'
const count = ref(1)
const double = computed(() => count.value * 2)
</script>
```
## Disable Auto-imports
In case you want to disable auto-imports, you can set `imports.autoImport` to `false`.
```ts [nuxt.config.ts]
export default defineNuxtConfig({
imports: {
autoImport: false
}
})
```
This will disable implicit auto imports completely but it's still possible to use [Explicit Imports](#explicit-imports).