shared

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

shared/ 目录允许你共享可在 Vue 应用和 Nitro 服务器中使用的代码。

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

shared/ 目录在 Nuxt v3.14+ 版本中可用。
shared/ 目录中的代码无法导入任何 Vue 或 Nitro 代码。
Nuxt v3 默认不启用自动导入功能,以防止对现有项目造成重大更改。¥Auto-imports are not enabled by default in Nuxt v3 to prevent breaking changes in existing projects.要使用这些自动导入的实用程序和类型,你必须先安装 nuxt.config.ts 中设置 future.compatibilityVersion: 4。¥To use these auto-imported utils and types, you must first set future.compatibilityVersion: 4 in your nuxt.config.ts.

用法

¥Usage

方法 1:命名导出

¥Method 1: Named export

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

方法 2:默认导出

¥Method 2: Default export

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

现在你可以在 Nuxt 应用和 server/ 目录中使用 auto-imported 实用程序。

¥You can now use auto-imported utilities in your Nuxt app and server/ directory.

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')
  }
})

如何扫描文件

¥How Files Are Scanned

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

¥Only files in the shared/utils/ and shared/types/ directories will be auto-imported. Files nested within subdirectories of these directories will not be auto-imported unless you add these directories to imports.dirs and nitro.imports.dirs.

shared/utilsshared/types 自动导入的工作方式和扫描方式与 composables/utils/ 目录相同。
Read more in Docs > Guide > Directory Structure > 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.d.ts           # Auto-imported

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

¥Any other files you create in the shared/ folder must be manually imported using the #shared alias (automatically configured by 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 > Guide > Concepts > Auto Imports.