shared

使用 shared/ 目录在 Vue 应用和 Nitro 服务器之间共享功能。

The shared/ directory allows you to share code that can be used in both the Vue app and the Nitro server.

The shared/ directory is available in Nuxt v3.14+.
Code in the shared/ directory cannot import any Vue or Nitro code.

用法

方法 1: 命名导出

shared/utils/capitalize.ts
export const capitalize = (input: string) => {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

方法 2: 默认导出

shared/utils/capitalize.ts
export default function (input: string) {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

现在你可以在 Nuxt 应用和 server/ 目录中使用这些自动导入 的工具了。

app/app.vue
<script setup lang="ts">
const hello = capitalize('hello')
</script>

<template>
  <div>
    {{ hello }}
  </div>
</template>
server/api/hello.get.ts
export default defineEventHandler((event) => {
  return {
    hello: capitalize('hello'),
  }
})

文件如何被扫描

只有位于 shared/utils/shared/types/ 目录下的文件会被自动导入。位于这些目录子目录中的文件不会被自动导入,除非你将这些子目录添加到 imports.dirsnitro.imports.dirs

shared/utilsshared/types 的自动导入和扫描方式与 app/composables/app/utils/ 目录的行为相同。
Read more in Docs > 4 X > Guide > Directory Structure > App > Composables#how Files Are Scanned.
Directory Structure
-| shared/
---| capitalize.ts        # Not auto-imported
---| formatters
-----| lower.ts           # Not auto-imported
---| utils/
-----| lower.ts           # Auto-imported
-----| formatters
-------| upper.ts         # Not auto-imported
---| types/
-----| bar.ts             # Auto-imported

你在 shared/ 文件夹中创建的其他任何文件,都必须使用 #shared 别名手动导入(该别名由 Nuxt 自动配置):

// For files directly in the shared directory
import capitalize from '#shared/capitalize'

// For files in nested directories
import lower from '#shared/formatters/lower'

// For files nested in a folder within utils
import upper from '#shared/utils/formatters/upper'

This alias ensures consistent imports across your application, regardless of the importing file's location.

Read more in Docs > 4 X > Guide > Concepts > Auto Imports.