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.dirs
和 nitro.imports.dirs
。
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.