mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-14 18:13:54 +00:00
f26a801775
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Roe <daniel@roe.dev>
50 lines
1.5 KiB
Markdown
50 lines
1.5 KiB
Markdown
---
|
|
title: 'utils'
|
|
head.title: 'utils/'
|
|
description: Use the utils/ directory to auto-import your utility functions throughout your application.
|
|
navigation.icon: i-ph-folder-duotone
|
|
---
|
|
|
|
The main purpose of the [`utils/` directory](/docs/guide/directory-structure/utils) is to allow a semantic distinction between your Vue composables and other auto-imported utility functions.
|
|
|
|
## Usage
|
|
|
|
**Method 1:** Using named export
|
|
|
|
```js [utils/index.ts]
|
|
export const { format: formatNumber } = Intl.NumberFormat('en-GB', {
|
|
notation: 'compact',
|
|
maximumFractionDigits: 1
|
|
})
|
|
```
|
|
|
|
**Method 2:** Using default export
|
|
|
|
```js [utils/random-entry.ts or utils/randomEntry.ts]
|
|
// It will be available as randomEntry() (camelCase of file name without extension)
|
|
export default function (arr: Array<any>) {
|
|
return arr[Math.floor(Math.random() * arr.length)]
|
|
}
|
|
```
|
|
|
|
You can now use auto imported utility functions in `.js`, `.ts` and `.vue` files
|
|
|
|
```vue [app.vue]
|
|
<template>
|
|
<p>{{ formatNumber(1234) }}</p>
|
|
</template>
|
|
```
|
|
|
|
:read-more{to="/docs/guide/concepts/auto-imports"}
|
|
|
|
:link-example{to="/docs/examples/features/auto-imports"}
|
|
|
|
::callout
|
|
The way `utils/` auto-imports work and are scanned is identical to the [`composables/`](/docs/guide/directory-structure/composables) directory.
|
|
::
|
|
|
|
::callout{color="amber" icon="i-ph-warning-duotone"}
|
|
These utils are only available within the Vue part of your app. :br
|
|
Only `server/utils` are auto-imported in the [`server/`](/docs/guide/directory-structure/server#server-utilities) directory.
|
|
::
|