---
title: "utils"
description: "在整个应用中使用 utils/ 目录来自动导入你的工具函数。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/utils"
---
# utils

> 在整个应用中使用 utils/ 目录来自动导入你的工具函数。

[`app/utils/` 目录](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/utils) 的主要用途是在语义上区分 Vue 组合式函数和其他自动导入的工具函数。

## 使用

**方法 1：** 使用命名导出

```ts twoslash [utils/index.ts]
export const { format: formatNumber } = Intl.NumberFormat('en-GB', {
  notation: 'compact',
  maximumFractionDigits: 1,
})
```

**方法 2：** 使用默认导出

```ts twoslash [utils/random-entry.ts or utils/randomEntry.ts]
// 它将作为 randomEntry()（文件名的小驼峰形式，不带扩展名）可用
export default function (arr: Array<any>) {
  return arr[Math.floor(Math.random() * arr.length)]
}
```

你现在可以在 `.js`、`.ts` 和 `.vue` 文件中使用自动导入的工具函数

```vue [app/app.vue]
<template>
  <p>{{ formatNumber(1234) }}</p>
</template>
```

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/guide/concepts/auto-imports"}
::

::link-example{to="https://nuxt.zhcndoc.com/docs/examples/features/auto-imports"}
::

::tip
`app/utils/` 的自动导入方式及扫描方式与 [`app/composables/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/composables) 目录相同。
::

::important
这些工具函数仅在应用的 Vue 部分中可用。:br
只有 `server/utils` 会在 [`server/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/server#server-utilities) 目录中自动导入。
::

::tip
类型也可以用同样的方式自动导入。将仅供应用使用的类型放在 `app/types/` 中，将仅供服务器使用的类型放在 [`server/types/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/server#server-types) 中，并将两者共用的类型放在 [`shared/types/`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/shared) 中。
::


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
