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.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
export const capitalize = (input: string) => {
return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}
方法 2:默认导出
¥Method 2: Default export
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.
<script setup lang="ts">
const hello = capitalize('hello')
</script>
<template>
<div>
{{ hello }}
</div>
</template>
export default defineEventHandler((event) => {
return {
hello: capitalize('hello')
}
})
如何扫描文件
¥How Files Are Scanned
只有 shared/utils/ 和 shared/types/ 目录中的文件会被自动导入。除非你将这些目录添加到 imports.dirs 和 nitro.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/
---| 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.