mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 23:22:02 +00:00
docs: first pass at the shared directory documentation
This commit is contained in:
parent
8feafa9554
commit
cb9a4ec847
77
docs/2.guide/2.directory-structure/1.shared.md
Normal file
77
docs/2.guide/2.directory-structure/1.shared.md
Normal file
@ -0,0 +1,77 @@
|
||||
---
|
||||
title: 'shared'
|
||||
head.title: 'shared/'
|
||||
description: Use the shared/ directory to share functionality between the Vue app and the Nitro server.
|
||||
navigation.icon: i-ph-folder
|
||||
---
|
||||
|
||||
The `shared/` directory allows you to share code that can be used in both the Vue app and the Nitro server.
|
||||
|
||||
::tip
|
||||
The `shared/` directory is available in Nuxt v3.14+.
|
||||
::
|
||||
|
||||
::important
|
||||
Code in the shared directory cannot import any Vue or nitro code.
|
||||
::
|
||||
|
||||
## Usage
|
||||
|
||||
**Method 1:** Using named export
|
||||
|
||||
```ts twoslash [shared/utils/capitalize.ts]
|
||||
export const capitalize = (input: string) => {
|
||||
return input[0].toUpperCase() + input.slice(1)
|
||||
}
|
||||
```
|
||||
|
||||
**Method 2:** Using default export
|
||||
|
||||
```ts twoslash [shared/utils/capitalize.ts]
|
||||
export default function capitalize (input: string) {
|
||||
return input[0].toUpperCase() + input.slice(1)
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:** You can now use auto-imported utility functions in `.js`, `.ts` and `.vue` files within your Vue app and the `server/` directory.
|
||||
|
||||
If you are using `compatibilityVersion: 4`, you can use the auto-imported functions in the `app/` directory.
|
||||
|
||||
```vue [app.vue]
|
||||
<script setup lang="ts">
|
||||
const hello = capitalize('hello')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
{{ hello }}
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
```ts [server/api/hello.get.ts]
|
||||
export default defineEventHandler((event) => {
|
||||
return {
|
||||
hello: capitalize('hello')
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Auto Imports
|
||||
|
||||
Only files in the `shared/utils/` and `shared/types/` directories will be auto-imported.
|
||||
|
||||
```bash [Directory Structure]
|
||||
-| shared/
|
||||
---| foo.ts # Not auto-imported
|
||||
---| utils/
|
||||
-----| bar.ts # Auto-imported
|
||||
---| types/
|
||||
-----| bar.d.ts # Auto-imported
|
||||
```
|
||||
|
||||
Any other files you create in the shared folder must be manually imported using `import foo from '#shared/foo'`.
|
||||
|
||||
This includes nested directories. A file located at `shared/formatters/lower.ts` will be imported with `import lower from '#shared/formatters/lower'`.
|
||||
|
||||
:read-more{to="/docs/guide/concepts/auto-imports"}
|
Loading…
Reference in New Issue
Block a user