Lzh on GitHub

shared

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

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

shared/ 目录在 Nuxt v3.14+ 中可用。

shared/ 目录中的代码不能导入任何 Vue 或 Nitro 代码。

Nuxt v3 默认不启用自动导入,以防止现有项目出现重大更改。要使用这些自动导入的实用工具和类型,你必须首先 nuxt.config.ts 中设置 future.compatibilityVersion: 4

用法

方法 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.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 自动导入的工作方式和扫描方式与 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 自动配置)手动导入:

// 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'

无论导入文件的位置如何,此别名都可确保你的应用程序中的导入保持一致。

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