Skip to content

Commit

Permalink
docs: document auto-imports and avoid #app and #imports in exampl…
Browse files Browse the repository at this point in the history
…es (nuxt#3296)
  • Loading branch information
clemcode authored Feb 18, 2022
1 parent 916ab56 commit 22c3e33
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 50 deletions.
5 changes: 1 addition & 4 deletions docs/content/1.getting-started/3.bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
::
Expand Down Expand Up @@ -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`
Expand All @@ -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',
})
Expand Down
37 changes: 8 additions & 29 deletions docs/content/1.getting-started/4.bridge-composition-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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`
Expand All @@ -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`
Expand All @@ -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(() => {
Expand All @@ -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')
Expand All @@ -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()
Expand All @@ -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.)
::
Expand Down Expand Up @@ -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!
Expand All @@ -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'))
Expand All @@ -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',
})
Expand All @@ -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,
Expand All @@ -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',
})
Expand Down
58 changes: 58 additions & 0 deletions docs/content/2.concepts/4.auto-imports.md
Original file line number Diff line number Diff line change
@@ -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>
```
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
::
Expand Down
2 changes: 0 additions & 2 deletions docs/content/3.docs/1.usage/4.nuxt-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 1 addition & 4 deletions docs/content/3.docs/2.directory-structure/10.pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 0 additions & 5 deletions docs/content/3.docs/2.directory-structure/11.plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand All @@ -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: {
Expand Down Expand Up @@ -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) => {
Expand Down
6 changes: 1 addition & 5 deletions docs/content/3.docs/2.directory-structure/5.composables.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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')
}
Expand All @@ -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')
Expand Down
6 changes: 6 additions & 0 deletions docs/content/3.docs/4.advanced/2.modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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')
Expand All @@ -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 => {
Expand Down

0 comments on commit 22c3e33

Please sign in to comment.