docs: document auto-imports and avoid #app and #imports in examples (#3296)

This commit is contained in:
Clément Ollivier 2022-02-18 19:20:55 +01:00 committed by GitHub
parent 916ab563ce
commit 22c3e33c1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 76 additions and 50 deletions

View File

@ -136,7 +136,7 @@ You may also need to add `@vue/runtime-dom` as a devDependency if you are strugg
::
::alert
Keep in mind that all options extended from `./.nuxt/tsconfig.json` will be overwritten by the options defined in your `tsconfig.json`.
Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead Typescript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#app` not being recognized.
Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead Typescript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#imports` not being recognized.
In case you need to extend options provided by `./.nuxt/tsconfig.json` further, you can use the `alias` property withing your `nuxt.config`. `nuxi` will pick them up and extend `./.nuxt/tsconfig.json` accordingly.
::
@ -184,8 +184,6 @@ You can now migrate to the Nuxt 3 plugins API, which is slightly different in fo
Plugins now take only one argument (`nuxtApp`). You can find out more in [the docs](/docs/directory-structure/plugins).
```js
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.provide('injected', () => 'my injected function')
// now available on `nuxtApp.$injected`
@ -202,7 +200,6 @@ Nuxt Bridge provides a new Nuxt 3 meta API that can be accessed with a new `useM
```vue
<script setup>
import { useMeta } from '#app'
useMeta({
title: 'My Nuxt App',
})

View File

@ -35,11 +35,14 @@ Because some composables have been removed and don't yet have a replacement, thi
* `useStatic` has been removed. There is no current replacement. Feel free to raise a discussion if you have a use case for this.
* `reqRef` and `reqSsrRef`, which were deprecated, have now been removed entirely. Follow the instructions below regarding [ssrRef](#ssrref-and-shallowssrref) to replace this.
2. Remove any explicit imports of the basic Vue Composition API composables, or move them to import from `#imports` or `vue`.
2. Remove any explicit imports of the basic Vue Composition API composables.
::alert{type=info}
Nuxt Bridge [auto-imports](/concepts/auto-imports) Vue composables, you don't have to explicitly import them.
::
```diff
- import { ref, useContext } from '@nuxtjs/composition-api`
+ import { ref } from '#imports'
```
3. For each other composable you are using from `@nuxtjs/composition-api`, follow the steps below.
@ -48,7 +51,7 @@ Because some composables have been removed and don't yet have a replacement, thi
This was a type-helper stub function that is now removed.
Simply remove the `defineNuxtMiddleware` wrapper:
Remove the `defineNuxtMiddleware` wrapper:
```diff
- import { defineNuxtMiddleware } from '@nuxtjs/composition-api`
@ -68,9 +71,9 @@ export default <Middleware> function (ctx) { }
This was a type-helper stub function that is now removed.
You may also keep using Nuxt 2-style plugins, by simply removing the function (as with [defineNuxtMiddleware](#definenuxtmiddleware)).
You may also keep using Nuxt 2-style plugins, by removing the function (as with [defineNuxtMiddleware](#definenuxtmiddleware)).
Simply remove the `defineNuxtPlugin` wrapper:
Remove the `defineNuxtPlugin` wrapper:
```diff
- import { defineNuxtPlugin } from '@nuxtjs/composition-api`
@ -96,7 +99,6 @@ This function has been removed, but its use cases can be met by using `useNuxtAp
```diff
- import { onGlobalSetup } from '@nuxtjs/composition-api'
+ import { defineNuxtPlugin } from '#app'
- export default () => {
- onGlobalSetup(() => {
@ -116,7 +118,6 @@ The key differences are that you must provide a _key_ for this state (which prev
```diff
- import { ssrRef } from '@nuxtjs/composition-api'
+ import { useState } from '#app'
- const ref1 = ssrRef('initialData')
- const ref2 = ssrRef(() => 'factory function')
@ -142,7 +143,6 @@ The only key difference is that `useRoute` no longer returns a computed property
```diff
- import { useRouter, useRoute } from '@nuxtjs/composition-api'
+ import { useRouter, useRoute } from '#imports'
const router = useRouter()
const route = useRoute()
@ -157,34 +157,18 @@ In order to access Vuex store instance, you can use `useNuxtApp().$store`.
```diff
- import { useStore } from '@nuxtjs/composition-api`
+ import { useNuxtApp } from '#app'
+ const { $store } = useNuxtApp()
```
```vue
<script>
import { useNuxtApp } from '#app'
const { $store } = useNuxtApp()
</script>
```
### `useContext` and `withContext`
You can access injected helpers using `useNuxtApp`.
```diff
- import { useContext } from '@nuxtjs/composition-api`
+ import { useNuxtApp } from '#app'
+ const { $axios } = useNuxtApp()
```
```vue
<script>
import { useNuxtApp } from '#app'
const { $axios } = useNuxtApp()
</script>
```
::alert{icon=👉}
`useNuxtApp()` also provides a key called `nuxt2Context` which contains all the same properties you would normally access from Nuxt 2 context, but it's advised _not_ to use this directly, as it won't exist in Nuxt 3. Instead, see if there is another way to access what you need. (If not, please raise a feature request or discussion.)
::
@ -213,7 +197,6 @@ Migrating to the new composables from `useAsync`:
```diff
<script setup>
- import { useAsync } from '@nuxtjs/composition-api'
+ import { useLazyAsyncData, useLazyFetch } from '#app'
- const posts = useAsync(() => $fetch('/api/posts'))
+ const { data: posts } = useLazyAsyncData('posts', () => $fetch('/api/posts'))
+ // or, more simply!
@ -226,7 +209,6 @@ Migrating to the new composables from `useFetch`:
```diff
<script setup>
- import { useFetch } from '@nuxtjs/composition-api'
+ import { useLazyAsyncData, useLazyFetch } from '#app'
- const posts = ref([])
- const { fetch } = useFetch(() => { posts.value = await $fetch('/api/posts') })
+ const { data: posts, refresh } = useLazyAsyncData('posts', () => $fetch('/api/posts'))
@ -246,7 +228,6 @@ In order to interact with `vue-meta`, you may use `useNuxt2Meta`, which will wor
```diff
<script setup>
- import { useMeta } from '@nuxtjs/composition-api'
+ import { useNuxt2Meta } from '#app'
useNuxt2Meta({
title: 'My Nuxt App',
})
@ -257,7 +238,6 @@ You can also pass in computed values or refs, and the meta values will be update
```ts
<script setup>
import { useNuxt2Meta } from '#app'
const title = ref('my title')
useNuxt2Meta({
title,
@ -275,7 +255,6 @@ Nuxt Bridge also provides a Nuxt 3-compatible meta implementation that can be ac
```diff
<script setup>
- import { useMeta } from '@nuxtjs/composition-api'
+ import { useMeta } from '#app'
useMeta({
title: 'My Nuxt App',
})

View File

@ -0,0 +1,58 @@
# 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.
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}
💡 In the documentation, every function that is not explicitly imported is auto-imported by Nuxt and can be used as-is in your code.
::
::alert{type=info}
🚧 We are working on a proper API reference that will include every Nuxt auto-imports. For now, you can find a reference on the framework repository: [github.com/nuxt/framework/blob/main/packages/nuxt3/src/auto-imports/imports.ts](https://github.com/nuxt/framework/blob/main/packages/nuxt3/src/auto-imports/imports.ts)
::
## Nuxt auto-imports
Nuxt auto-imports functions and composables to perform [data fetching](/docs/usage/data-fetching), get access to the [app context](/docs/usage/nuxt-app) and [runtime config](/docs/usage/runtime-config), manage [state](/docs/usage/state) or define components and plugins.
These functions can be used in components, composables or 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>
```
## Directory based auto-imports
Nuxt directly auto-imports files created in defined directories:
- `components/` for [Vue components](/docs/directory-structure/components).
- `composables/` for [Vue composables](/docs/directory-structure/composables).
## Explicit imports
Every Nuxt auto-import is exposed by 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>
```

View File

@ -31,7 +31,7 @@ Nitro also [auto-generates types](/concepts/server-engine#typed-api-routes) for
::
::alert
Keep in mind that all options extended from `./.nuxt/tsconfig.json` will be overwritten by the options defined in your `tsconfig.json`.
Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead Typescript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#app` not being recognized.
Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead Typescript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#imports` not being recognized.
In case you need to extend options provided by `./.nuxt/tsconfig.json` further, you can use the `alias` property within your `nuxt.config`. `nuxi` will pick them up and extend `./.nuxt/tsconfig.json` accordingly.
::

View File

@ -9,8 +9,6 @@ In Nuxt 2, this was referred to as [Nuxt context](https://nuxtjs.org/docs/intern
Within composables, plugins and components you can access `nuxtApp` with `useNuxtApp`:
```js
import { useNuxtApp } from '#app'
function useMyComposable () {
const nuxtApp = useNuxtApp()
// access runtime nuxt app instance

View File

@ -48,11 +48,8 @@ admins 123
If you want to access the route using Composition API, there is a global `useRoute` function that will allow you to access the route just like `this.$route` in the Options API.
```js
```vue
<script setup>
// This import statement is optional since it's automatically imported by Nuxt.
// import { useRoute } from '#imports'
const route = useRoute()
if (route.params.group === 'admins' && !route.params.id) {

View File

@ -34,8 +34,6 @@ Only `myPlugin.ts` and `myOtherPlugin/index.ts` would be registered.
The only argument passed to a plugin is [`nuxtApp`](/docs/usage/nuxt-app).
```ts
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(nuxtApp => {
// Doing something with nuxtApp
})
@ -46,8 +44,6 @@ export default defineNuxtPlugin(nuxtApp => {
If you would like to provide a helper on the `NuxtApp` instance, just return it from the plugin under a `provide` key. For example:
```ts
import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin(() => {
return {
provide: {
@ -115,7 +111,6 @@ yarn add --dev vue-gtag-next
Then create a plugin file `plugins/vue-gtag.client.js`.
```ts
import { defineNuxtPlugin } from '#app'
import VueGtag from 'vue-gtag-next'
export default defineNuxtPlugin((nuxtApp) => {

View File

@ -6,7 +6,7 @@ head.title: Composables directory
# Composables directory
Nuxt 3 supports `composables/` directory to automatically import your Vue composables into your application using auto-imports!
Nuxt 3 supports `composables/` directory to automatically import your Vue composables into your application using [auto-imports](/concepts/auto-imports)!
## How files are scanned
@ -27,8 +27,6 @@ Only `useFoo.ts` and `useBar/index.ts` would be searched for imports - and if th
## Example: (using named export)
```js [composables/useFoo.ts]
import { useState } from '#app'
export const useFoo = () => {
return useState('foo', () => 'bar')
}
@ -37,8 +35,6 @@ export const useFoo = () => {
## Example: (using default export)
```js [composables/use-foo.ts or composables/useFoo.ts]
import { useState } from '#app'
// It will be available as useFoo() (camelCase of file name without extension)
export default function () {
return useState('foo', () => 'bar')

View File

@ -72,6 +72,8 @@ export default defineNuxtConfig({
Creating Nuxt modules involves tedious and common tasks. [Nuxt Kit](/docs/advanced/kit), provides a convenient and standard API to define Nuxt modules using `defineNuxtModule`:
```js
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
// Usually npm package name of your module
@ -190,6 +192,8 @@ export default defineNuxtModule<ModuleOptions>({
If your module will provide a CSS library, make sure to check if the user already included the library to avoid duplicates and add an option to disable the CSS library in the module.
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.options.css.push('font-awesome/css/font-awesome.css')
@ -202,6 +206,8 @@ export default defineNuxtModule({
If your module opens handles or starts a watcher, we should close it when the nuxt lifecycle is done. For this, we can use the `close` hook:
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async nuxt => {