This commit is contained in:
Your Name
2026-08-11 17:41:36 +08:00
parent cfe4c82c90
commit 03fe4ddf9d
18771 changed files with 3617239 additions and 0 deletions
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,476 @@
# unplugin-auto-import
[![NPM version](https://img.shields.io/npm/v/unplugin-auto-import?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-auto-import)
Auto import APIs on-demand for Vite, Webpack, Rspack, Rollup and esbuild. With TypeScript support. Powered by [unplugin](https://github.com/unjs/unplugin).
---
without
```ts
import { computed, ref } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
with
```ts
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
---
without
```tsx
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
with
```tsx
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
## Install
```bash
npm i -D unplugin-auto-import
```
<details>
<summary>Vite</summary><br>
```ts
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ }),
],
})
```
Example: [`playground/`](./playground/)
<br></details>
<details>
<summary>Rollup</summary><br>
```ts
// rollup.config.js
import AutoImport from 'unplugin-auto-import/rollup'
export default {
plugins: [
AutoImport({ /* options */ }),
// other plugins
],
}
```
<br></details>
<details>
<summary>Webpack</summary><br>
```ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Rspack</summary><br>
```ts
// rspack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/rspack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Nuxt</summary><br>
> You **don't need** this plugin for Nuxt, it's already built-in.
<br></details>
<details>
<summary>Vue CLI</summary><br>
```ts
// vue.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
You can also rename the Vue configuration file to `vue.config.mjs` and use static import syntax (you should use latest `@vue/cli-service ^5.0.8`):
```ts
// vue.config.mjs
import AutoImport from 'unplugin-auto-import/webpack'
export default {
configureWebpack: {
plugins: [
AutoImport({ /* options */ }),
],
},
}
```
<br></details>
<details>
<summary>Quasar</summary><br>
```ts
// vite.config.js [Vite]
import AutoImport from 'unplugin-auto-import/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ })
]
})
```
```ts
// quasar.conf.js [Webpack]
const AutoImportPlugin = require('unplugin-auto-import/webpack').default
module.exports = {
build: {
chainWebpack(chain) {
chain.plugin('unplugin-auto-import').use(
AutoImportPlugin({ /* options */ }),
)
},
},
}
```
<br></details>
<details>
<summary>esbuild</summary><br>
```ts
// esbuild.config.js
import { build } from 'esbuild'
import AutoImport from 'unplugin-auto-import/esbuild'
build({
/* ... */
plugins: [
AutoImport({
/* options */
}),
],
})
```
<br></details>
<details>
<summary>Astro</summary><br>
```ts
// astro.config.mjs
import AutoImport from 'unplugin-auto-import/astro'
export default defineConfig({
integrations: [
AutoImport({
/* options */
})
],
})
```
<br></details>
## Configuration
```ts
AutoImport({
// targets to transform
include: [
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
/\.vue$/,
/\.vue\?vue/, // .vue
/\.md$/, // .md
],
// global imports to register
imports: [
// presets
'vue',
'vue-router',
// custom
{
'@vueuse/core': [
// named imports
'useMouse', // import { useMouse } from '@vueuse/core',
// alias
['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
],
'axios': [
// default imports
['default', 'axios'], // import { default as axios } from 'axios',
],
'[package-name]': [
'[import-names]',
// alias
['[from]', '[alias]'],
],
},
// example type import
{
from: 'vue-router',
imports: ['RouteLocationRaw'],
type: true,
},
],
// Array of strings of regexes that contains imports meant to be filtered out.
ignore: [
'useMouse',
'useFetch'
],
// Enable auto import by filename for default module exports under directories
defaultExportByFilename: false,
// Options for scanning directories for auto import
dirsScanOptions: {
types: true // Enable auto import the types under the directories
},
// Auto import for module exports under directories
// by default it only scan one level of modules under the directory
dirs: [
'./hooks',
'./composables', // only root modules
'./composables/**', // all nested modules
// ...
{
glob: './hooks',
types: true // enable import the types
},
{
glob: './composables',
types: false // If top level dirsScanOptions.types importing enabled, just only disable this directory
}
// ...
],
// Filepath to generate corresponding .d.ts file.
// Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
// Set `false` to disable.
dts: './auto-imports.d.ts',
// Array of strings of regexes that contains imports meant to be ignored during
// the declaration file generation. You may find this useful when you need to provide
// a custom signature for a function.
ignoreDts: [
'ignoredFunction',
/^ignore_/
],
// Auto import inside Vue template
// see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
vueTemplate: false,
// Auto import directives inside Vue template
// see https://github.com/unjs/unimport/pull/374
vueDirectives: undefined,
// Custom resolvers, compatible with `unplugin-vue-components`
// see https://github.com/antfu/unplugin-auto-import/pull/23/
resolvers: [
/* ... */
],
// Include auto-imported packages in Vite's `optimizeDeps` options
// Recommend to enable
viteOptimizeDeps: true,
// Inject the imports at the end of other imports
injectAtEnd: true,
// Generate corresponding .eslintrc-auto-import.json file.
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
eslintrc: {
enabled: false, // Default `false`
// provide path ending with `.mjs` or `.cjs` to generate the file with the respective format
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
},
// Generate corresponding .biomelintrc-auto-import.json file.
// biomejs extends Docs - https://biomejs.dev/guides/how-biome-works/#the-extends-option
biomelintrc: {
enabled: false, // Default `false`
filepath: './.biomelintrc-auto-import.json', // Default `./.biomelintrc-auto-import.json`
},
// Save unimport items into a JSON file for other tools to consume
dumpUnimportItems: './auto-imports.json', // Default `false`
})
```
Refer to the [type definitions](./src/types.ts) for more options.
## Presets
See [src/presets](./src/presets).
## Package Presets
We only provide presets for the most popular packages, to use any package not included here you can install it as dev dependency and add it to the `packagePresets` array option:
```ts
AutoImport({
/* other options */
packagePresets: ['detect-browser-es'/* other local package names */]
})
```
You can check the [Svelte example](./examples/vite-svelte) for a working example registering `detect-browser-es` package preset and auto importing `detect` function in [App.svelte](./examples/vite-svelte/src/App.svelte).
Please refer to the [unimport PackagePresets jsdocs](https://github.com/unjs/unimport/blob/main/src/types.ts) for more information about options like `ignore` or `cache`.
**Note**: ensure local packages used have package exports configured properly, otherwise the corresponding modules exports will not be detected.
## TypeScript
In order to properly hint types for auto-imported APIs
<table>
<tr>
<td width="400px" valign="top">
1. Enable `options.dts` so that `auto-imports.d.ts` file is automatically generated
2. Make sure `auto-imports.d.ts` is not excluded in `tsconfig.json`
</td>
<td width="600px"><br>
```ts
AutoImport({
dts: true // or a custom path
})
```
</td>
</tr>
</table>
## ESLint
> 💡 When using TypeScript, we recommend to **disable** `no-undef` rule directly as TypeScript already check for them and you don't need to worry about this.
If you have encountered ESLint error of `no-undef`:
<table>
<tr>
<td width="400px">
1. Enable `eslintrc.enabled`
</td>
<td width="600px"><br>
```ts
AutoImport({
eslintrc: {
enabled: true, // <-- this
},
})
```
</td></tr></table>
<table><tr><td width="400px">
2. Update your `eslintrc`:
[Extending Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files)
</td>
<td width="600px"><br>
```ts
// .eslintrc.js
module.exports = {
extends: [
'./.eslintrc-auto-import.json',
],
}
```
</td>
</tr>
</table>
## FAQ
### Compare to [`unimport`](https://github.com/unjs/unimport)
From v0.8.0, `unplugin-auto-import` **uses** `unimport` underneath. `unimport` is designed to be a lower-level tool (it also powered Nuxt's auto import). You can think `unplugin-auto-import` is a wrapper of it that provides more user-friendly config APIs and capabilities like resolvers. Development of new features will mostly happen in `unimport` from now.
### Compare to [`vue-global-api`](https://github.com/antfu/vue-global-api)
You can think of this plugin as a successor to `vue-global-api`, but offering much more flexibility and bindings with libraries other than Vue (e.g. React).
###### Pros
- Flexible and customizable
- Tree-shakable (on-demand transforming)
- No global population
###### Cons
- Relying on build tools integrations (while `vue-global-api` is pure runtime) - but hey, we have supported quite a few of them already!
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
@@ -0,0 +1,179 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const $: typeof import('vue/macros')['$']
const $$: typeof import('vue/macros')['$$']
const $computed: typeof import('vue/macros')['$computed']
const $customRef: typeof import('vue/macros')['$customRef']
const $ref: typeof import('vue/macros')['$ref']
const $shallowRef: typeof import('vue/macros')['$shallowRef']
const $toRef: typeof import('vue/macros')['$toRef']
const EffectScope: typeof import('vue')['EffectScope']
const THREE: typeof import('three.js')
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const afterAll: typeof import('vitest')['afterAll']
const afterEach: typeof import('vitest')['afterEach']
const afterUpdate: typeof import('svelte')['afterUpdate']
const assert: typeof import('vitest')['assert']
const backIn: typeof import('svelte/easing')['backIn']
const backInOut: typeof import('svelte/easing')['backInOut']
const backOut: typeof import('svelte/easing')['backOut']
const beforeAll: typeof import('vitest')['beforeAll']
const beforeEach: typeof import('vitest')['beforeEach']
const beforeUpdate: typeof import('svelte')['beforeUpdate']
const blur: typeof import('svelte/transition')['blur']
const bounceIn: typeof import('svelte/easing')['bounceIn']
const bounceInOut: typeof import('svelte/easing')['bounceInOut']
const bounceOut: typeof import('svelte/easing')['bounceOut']
const chai: typeof import('vitest')['chai']
const circIn: typeof import('svelte/easing')['circIn']
const circInOut: typeof import('svelte/easing')['circInOut']
const circOut: typeof import('svelte/easing')['circOut']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const createEventDispatcher: typeof import('svelte')['createEventDispatcher']
const createPinia: typeof import('pinia')['createPinia']
const createRef: typeof import('react')['createRef']
const crossfade: typeof import('svelte/transition')['crossfade']
const cubicIn: typeof import('svelte/easing')['cubicIn']
const cubicInOut: typeof import('svelte/easing')['cubicInOut']
const cubicOut: typeof import('svelte/easing')['cubicOut']
const customDefault: typeof import('custom')['default']
const customDefaultAlias: typeof import('custom')['default']
const customNamed: typeof import('custom')['customNamed']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const derived: typeof import('svelte/store')['derived']
const describe: typeof import('vitest')['describe']
const draw: typeof import('svelte/transition')['draw']
const effectScope: typeof import('vue')['effectScope']
const elasticIn: typeof import('svelte/easing')['elasticIn']
const elasticInOut: typeof import('svelte/easing')['elasticInOut']
const elasticOut: typeof import('svelte/easing')['elasticOut']
const expect: typeof import('vitest')['expect']
const expoIn: typeof import('svelte/easing')['expoIn']
const expoInOut: typeof import('svelte/easing')['expoInOut']
const expoOut: typeof import('svelte/easing')['expoOut']
const fade: typeof import('svelte/transition')['fade']
const flip: typeof import('svelte/animate')['flip']
const fly: typeof import('svelte/transition')['fly']
const forwardRef: typeof import('react')['forwardRef']
const get: typeof import('svelte/store')['get']
const getActivePinia: typeof import('pinia')['getActivePinia']
const getAllContexts: typeof import('svelte')['getAllContexts']
const getContext: typeof import('svelte')['getContext']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const hasContext: typeof import('svelte')['hasContext']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const it: typeof import('vitest')['it']
const lazy: typeof import('react')['lazy']
const linear: typeof import('svelte/easing')['linear']
const mapActions: typeof import('pinia')['mapActions']
const mapGetters: typeof import('pinia')['mapGetters']
const mapState: typeof import('pinia')['mapState']
const mapStores: typeof import('pinia')['mapStores']
const mapWritableState: typeof import('pinia')['mapWritableState']
const markRaw: typeof import('vue')['markRaw']
const memo: typeof import('react')['memo']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onDestroy: typeof import('svelte')['onDestroy']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMount: typeof import('svelte')['onMount']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const quadIn: typeof import('svelte/easing')['quadIn']
const quadInOut: typeof import('svelte/easing')['quadInOut']
const quadOut: typeof import('svelte/easing')['quadOut']
const quartIn: typeof import('svelte/easing')['quartIn']
const quartInOut: typeof import('svelte/easing')['quartInOut']
const quartOut: typeof import('svelte/easing')['quartOut']
const quintIn: typeof import('svelte/easing')['quintIn']
const quintInOut: typeof import('svelte/easing')['quintInOut']
const quintOut: typeof import('svelte/easing')['quintOut']
const reactive: typeof import('vue')['reactive']
const readable: typeof import('svelte/store')['readable']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const scale: typeof import('svelte/transition')['scale']
const setActivePinia: typeof import('pinia')['setActivePinia']
const setContext: typeof import('svelte')['setContext']
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const sineIn: typeof import('svelte/easing')['sineIn']
const sineInOut: typeof import('svelte/easing')['sineInOut']
const sineOut: typeof import('svelte/easing')['sineOut']
const slide: typeof import('svelte/transition')['slide']
const spring: typeof import('svelte/motion')['spring']
const startTransition: typeof import('react')['startTransition']
const storeToRefs: typeof import('pinia')['storeToRefs']
const suite: typeof import('vitest')['suite']
const test: typeof import('vitest')['test']
const tick: typeof import('svelte')['tick']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const tweened: typeof import('svelte/motion')['tweened']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCallback: typeof import('react')['useCallback']
const useContext: typeof import('react')['useContext']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useDebugValue: typeof import('react')['useDebugValue']
const useDeferredValue: typeof import('react')['useDeferredValue']
const useDialogPluginComponent: typeof import('quasar')['useDialogPluginComponent']
const useEffect: typeof import('react')['useEffect']
const useFormChild: typeof import('quasar')['useFormChild']
const useId: typeof import('react')['useId']
const useImperativeHandle: typeof import('react')['useImperativeHandle']
const useInsertionEffect: typeof import('react')['useInsertionEffect']
const useLayoutEffect: typeof import('react')['useLayoutEffect']
const useMemo: typeof import('react')['useMemo']
const useMeta: typeof import('quasar')['useMeta']
const useModel: typeof import('vue')['useModel']
const useQuasar: typeof import('quasar')['useQuasar']
const useReducer: typeof import('react')['useReducer']
const useRef: typeof import('react')['useRef']
const useSlots: typeof import('vue')['useSlots']
const useState: typeof import('react')['useState']
const useSyncExternalStore: typeof import('react')['useSyncExternalStore']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const useTransition: typeof import('react')['useTransition']
const vi: typeof import('vitest')['vi']
const vitest: typeof import('vitest')['vitest']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
const writable: typeof import('svelte/store')['writable']
}
@@ -0,0 +1,21 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(_chunkA6NGEVNDcjs.unplugin_default.vite(options));
}
}
};
}
exports.default = astro_default;
@@ -0,0 +1,13 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };
@@ -0,0 +1,13 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };
@@ -0,0 +1,21 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(unplugin_default.vite(options));
}
}
};
}
export {
astro_default as default
};
@@ -0,0 +1,608 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/presets/index.ts
var _unimport = require('unimport');
// src/presets/ahooks.ts
var _fs = require('fs');
var _localpkg = require('local-pkg');
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = _localpkg.resolveModule.call(void 0, "ahooks/metadata.json");
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/core/indexes.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vueuse-math.ts
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/index.ts
var presets = {
..._unimport.builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
exports.presets = presets;
@@ -0,0 +1,504 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _chunk6BSQ6ZKCcjs = require('./chunk-6BSQ6ZKC.cjs');
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
function toArray(array) {
array = array != null ? array : [];
return Array.isArray(array) ? array : [array];
}
var VOID = Symbol("p-void");
function slash(str) {
return str.replace(/\\/g, "/");
}
function throttle$1(delay, callback, options) {
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
var timeoutID;
var cancelled = false;
var lastExec = 0;
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
}
function cancel(options2) {
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
}
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
function clear() {
timeoutID = void 0;
}
if (!noLeading && debounceMode && !timeoutID) {
exec();
}
clearExistingTimeout();
if (debounceMode === void 0 && elapsed > delay) {
if (noLeading) {
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
exec();
}
} else if (noTrailing !== true) {
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel;
return wrapper;
}
function throttle(...args) {
return throttle$1(...args);
}
// src/core/unplugin.ts
var _localpkg = require('local-pkg');
var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
var _unplugin = require('unplugin');
// src/core/ctx.ts
var _fs = require('fs');
var _path = require('path');
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
var _unimport = require('unimport');
var _unpluginutils = require('unplugin-utils');
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
name: "unplugin-auto-import:resolvers",
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function createContext(options = {}, root = _process2.default.cwd()) {
var _a, _b, _c;
root = slash(root);
const {
dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript"),
dirsScanOptions,
dirs,
vueDirectives,
vueTemplate
} = options;
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = _unimport.createUnimport.call(void 0, {
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
dirsScanOptions: {
...dirsScanOptions,
cwd: root
},
dirs,
injectAtEnd,
parser: options.parser,
addons: {
addons: [
resolversAddon(resolvers),
{
name: "unplugin-auto-import:dts",
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
${dts2}`.trim()}
`;
}
}
],
vueDirectives,
vueTemplate
}
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = _unpluginutils.createFilter.call(void 0,
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = _path.dirname.call(void 0, file);
const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
const related = slash(_path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
return await _fs.promises.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
let lastUnimportItems;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
if (dumpUnimportItems) {
promises.push(
unimport.getImports().then((items) => {
if (!dumpUnimportItems)
return;
const content = JSON.stringify(items, null, 2);
if (content !== lastUnimportItems) {
lastUnimportItems = content;
return writeFile(dumpUnimportItems, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await unimport.scanImportsFromDir();
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new (0, _magicstring2.default)(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(toArray(map).map(async (definition) => {
if (typeof definition === "string") {
if (!_chunk6BSQ6ZKCcjs.presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = _chunk6BSQ6ZKCcjs.presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await _unimport.resolvePreset.call(void 0, definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (options.viteOptimizeDeps === false)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && _localpkg.isPackageExists.call(void 0, i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => _picomatch2.default.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
exports.unplugin_default = unplugin_default;
@@ -0,0 +1,608 @@
// src/presets/index.ts
import { builtinPresets } from "unimport";
// src/presets/ahooks.ts
import { readFileSync } from "node:fs";
import { resolveModule } from "local-pkg";
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = resolveModule("ahooks/metadata.json");
indexesJson = JSON.parse(readFileSync(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
import { readFileSync as readFileSync2 } from "node:fs";
import process from "node:process";
import { resolveModule as resolveModule2 } from "local-pkg";
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = resolveModule2("@vueuse/core") || process.cwd();
const path = resolveModule2("@vueuse/core/indexes.json") || resolveModule2("@vueuse/metadata/index.json") || resolveModule2("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync2(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vueuse-math.ts
import { readFileSync as readFileSync3 } from "node:fs";
import process2 from "node:process";
import { resolveModule as resolveModule3 } from "local-pkg";
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = resolveModule3("@vueuse/core") || process2.cwd();
const path = resolveModule3("@vueuse/metadata/index.json") || resolveModule3("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync3(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/index.ts
var presets = {
...builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
export {
presets
};
@@ -0,0 +1,504 @@
import {
presets
} from "./chunk-DTT25XJ5.js";
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
function toArray(array) {
array = array != null ? array : [];
return Array.isArray(array) ? array : [array];
}
var VOID = Symbol("p-void");
function slash(str) {
return str.replace(/\\/g, "/");
}
function throttle$1(delay, callback, options) {
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
var timeoutID;
var cancelled = false;
var lastExec = 0;
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
}
function cancel(options2) {
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
}
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
function clear() {
timeoutID = void 0;
}
if (!noLeading && debounceMode && !timeoutID) {
exec();
}
clearExistingTimeout();
if (debounceMode === void 0 && elapsed > delay) {
if (noLeading) {
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
exec();
}
} else if (noTrailing !== true) {
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel;
return wrapper;
}
function throttle(...args) {
return throttle$1(...args);
}
// src/core/unplugin.ts
import { isPackageExists as isPackageExists2 } from "local-pkg";
import pm from "picomatch";
import { createUnplugin } from "unplugin";
// src/core/ctx.ts
import { existsSync, promises as fs } from "node:fs";
import { dirname, isAbsolute, relative, resolve } from "node:path";
import process from "node:process";
import { isPackageExists } from "local-pkg";
import MagicString from "magic-string";
import { createUnimport, resolvePreset } from "unimport";
import { createFilter } from "unplugin-utils";
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
name: "unplugin-auto-import:resolvers",
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function createContext(options = {}, root = process.cwd()) {
var _a, _b, _c;
root = slash(root);
const {
dts: preferDTS = isPackageExists("typescript"),
dirsScanOptions,
dirs,
vueDirectives,
vueTemplate
} = options;
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = createUnimport({
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
dirsScanOptions: {
...dirsScanOptions,
cwd: root
},
dirs,
injectAtEnd,
parser: options.parser,
addons: {
addons: [
resolversAddon(resolvers),
{
name: "unplugin-auto-import:dts",
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
${dts2}`.trim()}
`;
}
}
],
vueDirectives,
vueTemplate
}
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = createFilter(
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? resolve(root, "auto-imports.d.ts") : resolve(root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = dirname(file);
const originalContent = existsSync(file) ? await fs.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || isAbsolute(i.from)) {
const related = slash(relative(dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = existsSync(eslintrc.filepath) ? await fs.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await fs.mkdir(dirname(filePath), { recursive: true });
return await fs.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
let lastUnimportItems;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
if (dumpUnimportItems) {
promises.push(
unimport.getImports().then((items) => {
if (!dumpUnimportItems)
return;
const content = JSON.stringify(items, null, 2);
if (content !== lastUnimportItems) {
lastUnimportItems = content;
return writeFile(dumpUnimportItems, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await unimport.scanImportsFromDir();
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new MagicString(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(toArray(map).map(async (definition) => {
if (typeof definition === "string") {
if (!presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await resolvePreset(definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = createUnplugin((options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (options.viteOptimizeDeps === false)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && isPackageExists2(i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => pm.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
export {
unplugin_default
};
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/esbuild.ts
var esbuild_default = _chunkA6NGEVNDcjs.unplugin_default.esbuild;
exports.default = esbuild_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/esbuild.ts
var esbuild_default = unplugin_default.esbuild;
export {
esbuild_default as default
};
@@ -0,0 +1,7 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
exports.default = _chunkA6NGEVNDcjs.unplugin_default;
@@ -0,0 +1,9 @@
import * as unplugin from 'unplugin';
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
export { _default as default };
@@ -0,0 +1,9 @@
import * as unplugin from 'unplugin';
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
export { _default as default };
@@ -0,0 +1,7 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
export {
unplugin_default as default
};
@@ -0,0 +1,17 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/nuxt.ts
var _kit = require('@nuxt/kit');
var nuxt_default = _kit.defineNuxtModule.call(void 0, {
setup(options) {
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
_kit.addWebpackPlugin.call(void 0, _chunkA6NGEVNDcjs.unplugin_default.webpack(options));
_kit.addVitePlugin.call(void 0, _chunkA6NGEVNDcjs.unplugin_default.vite(options));
}
});
exports.default = nuxt_default;
@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
export { _default as default };
@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
export { _default as default };
@@ -0,0 +1,17 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/nuxt.ts
import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
var nuxt_default = defineNuxtModule({
setup(options) {
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
addWebpackPlugin(unplugin_default.webpack(options));
addVitePlugin(unplugin_default.vite(options));
}
});
export {
nuxt_default as default
};
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/rollup.ts
var rollup_default = _chunkA6NGEVNDcjs.unplugin_default.rollup;
exports.default = rollup_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/rollup.ts
var rollup_default = unplugin_default.rollup;
export {
rollup_default as default
};
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/rspack.ts
var rspack_default = _chunkA6NGEVNDcjs.unplugin_default.rspack;
exports.default = rspack_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/rspack.ts
var rspack_default = unplugin_default.rspack;
export {
rspack_default as default
};
@@ -0,0 +1 @@
"use strict";require('./chunk-6BSQ6ZKC.cjs');
@@ -0,0 +1,255 @@
import { Arrayable, Awaitable } from '@antfu/utils';
import * as unimport from 'unimport';
import { InlinePreset, PackagePreset, Import, UnimportOptions, AddonVueDirectivesOptions } from 'unimport';
import { FilterPattern } from 'unplugin-utils';
declare const presets: {
ahooks: () => ImportsMap;
'@vueuse/core': () => ImportsMap;
'@vueuse/math': () => ImportsMap;
'@vueuse/head': ImportsMap;
mobx: ImportsMap;
'mobx-react-lite': ImportsMap;
preact: ImportsMap;
quasar: ImportsMap;
react: ImportsMap;
'react-router': ImportsMap;
'react-router-dom': ImportsMap;
'react-i18next': ImportsMap;
svelte: ImportsMap;
'svelte/animate': ImportsMap;
'svelte/easing': ImportsMap;
'svelte/motion': ImportsMap;
'svelte/store': ImportsMap;
'svelte/transition': ImportsMap;
'vee-validate': ImportsMap;
vitepress: ImportsMap;
'vue-router': ImportsMap;
'vue-router/composables': ImportsMap;
vuex: ImportsMap;
'uni-app': ImportsMap;
'solid-js': ImportsMap;
'@solidjs/router': ImportsMap;
'solid-app-router': ImportsMap;
jotai: ImportsMap;
'jotai/utils': ImportsMap;
recoil: ImportsMap;
'@vue/composition-api': unimport.InlinePreset;
pinia: unimport.InlinePreset;
'vue-demi': unimport.InlinePreset;
'vue-i18n': unimport.InlinePreset;
'vue-router-composables': unimport.InlinePreset;
vue: unimport.InlinePreset;
'vue/macros': unimport.InlinePreset;
vitest: unimport.InlinePreset;
rxjs: unimport.InlinePreset;
'date-fns': unimport.InlinePreset;
};
type PresetName = keyof typeof presets;
interface ImportLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportExtended extends Import {
sideEffects?: SideEffectsInfo;
__source?: 'dir' | 'resolver';
}
type ImportNameAlias = [string, string];
type SideEffectsInfo = Arrayable<ResolverResult | string> | undefined;
interface ResolverResult {
as?: string;
name?: string;
from: string;
}
type ResolverFunction = (name: string) => Awaitable<string | ResolverResult | ImportExtended | null | undefined | void>;
interface ResolverResultObject {
type: 'component' | 'directive';
resolve: ResolverFunction;
}
/**
* Given a identifier name, returns the import path or an import object
*/
type Resolver = ResolverFunction | ResolverResultObject;
/**
* module, name, alias
*/
type ImportsMap = Record<string, (string | ImportNameAlias)[]>;
interface ScanDirExportsOptions {
/**
* Register type exports
*
* @default true
*/
types?: boolean;
}
/**
* Directory to search for import
*/
interface ScanDir {
glob: string;
types?: boolean;
}
type NormalizedScanDir = Required<ScanDir>;
type ESLintGlobalsPropValue = boolean | 'readonly' | 'readable' | 'writable' | 'writeable';
interface ESLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
/**
* @default true
*/
globalsPropValue?: ESLintGlobalsPropValue;
}
interface BiomeLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
}
interface Options {
/**
* Preset names or custom imports map
*
* @default []
*/
imports?: Arrayable<ImportsMap | PresetName | InlinePreset>;
/**
* Local package presets.
*
* Register local installed packages as a preset.
*
* @default []
* @see https://github.com/unplugin/unplugin-auto-import#package-presets
*/
packagePresets?: (PackagePreset | string)[];
/**
* Identifiers to be ignored
*/
ignore?: (string | RegExp)[];
/**
* These identifiers won't be put on the DTS file
*/
ignoreDts?: (string | RegExp)[];
/**
* Inject the imports at the end of other imports
*
* @default true
*/
injectAtEnd?: boolean;
/**
* Options for scanning directories for auto import
*/
dirsScanOptions?: ScanDirExportsOptions;
/**
* Path for directories to be auto imported
*/
dirs?: (string | ScanDir)[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: Arrayable<Arrayable<Resolver>>;
/**
* Parser to be used for parsing the source code.
*
* @see https://github.com/unjs/unimport#acorn-parser
* @default 'regex'
*/
parser?: UnimportOptions['parser'];
/**
* Filepath to generate corresponding .d.ts file.
* Default enabled when `typescript` is installed locally.
* Set `false` to disable.
*
* @default './auto-imports.d.ts'
*/
dts?: string | boolean;
/**
* Auto import inside Vue templates
*
* @see https://github.com/unjs/unimport/pull/15
* @see https://github.com/unjs/unimport/pull/72
* @default false
*/
vueTemplate?: boolean;
/**
* Enable auto import directives for Vue's SFC.
*
* Library authors should include `meta.vueDirective: true` in the import metadata.
*
* When using a local directives folder, provide the `isDirective`
* callback to check if the import is a Vue directive.
*
* @see https://github.com/unjs/unimport?tab=readme-ov-file#vue-directives-auto-import-and-typescript-declaration-generation
*/
vueDirectives?: true | AddonVueDirectivesOptions;
/**
* Set default export alias by file name
*
* @default false
*/
defaultExportByFilename?: boolean;
/**
* Rules to include transforming target.
*
* @default [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/]
*/
include?: FilterPattern;
/**
* Rules to exclude transforming target.
*
* @default [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
*/
exclude?: FilterPattern;
/**
* Generate corresponding .eslintrc-auto-import.json file.
*/
eslintrc?: ESLintrc;
/**
* Generate corresponding .biomelintrc.json file.
*/
biomelintrc?: BiomeLintrc;
/**
* Save unimport items into a JSON file for other tools to consume.
* Provide a filepath to save the JSON file.
*
* When set to `true`, it will save to `./.unimport-items.json`
*
* @default false
*/
dumpUnimportItems?: boolean | string;
/**
* Include auto-imported packages in Vite's `optimizeDeps` option
*
* @default true
*/
viteOptimizeDeps?: boolean;
}
export type { BiomeLintrc, ESLintGlobalsPropValue, ESLintrc, ImportExtended, ImportLegacy, ImportNameAlias, ImportsMap, NormalizedScanDir, Options, PresetName, Resolver, ResolverFunction, ResolverResult, ResolverResultObject, ScanDir, ScanDirExportsOptions, SideEffectsInfo };
@@ -0,0 +1,255 @@
import { Arrayable, Awaitable } from '@antfu/utils';
import * as unimport from 'unimport';
import { InlinePreset, PackagePreset, Import, UnimportOptions, AddonVueDirectivesOptions } from 'unimport';
import { FilterPattern } from 'unplugin-utils';
declare const presets: {
ahooks: () => ImportsMap;
'@vueuse/core': () => ImportsMap;
'@vueuse/math': () => ImportsMap;
'@vueuse/head': ImportsMap;
mobx: ImportsMap;
'mobx-react-lite': ImportsMap;
preact: ImportsMap;
quasar: ImportsMap;
react: ImportsMap;
'react-router': ImportsMap;
'react-router-dom': ImportsMap;
'react-i18next': ImportsMap;
svelte: ImportsMap;
'svelte/animate': ImportsMap;
'svelte/easing': ImportsMap;
'svelte/motion': ImportsMap;
'svelte/store': ImportsMap;
'svelte/transition': ImportsMap;
'vee-validate': ImportsMap;
vitepress: ImportsMap;
'vue-router': ImportsMap;
'vue-router/composables': ImportsMap;
vuex: ImportsMap;
'uni-app': ImportsMap;
'solid-js': ImportsMap;
'@solidjs/router': ImportsMap;
'solid-app-router': ImportsMap;
jotai: ImportsMap;
'jotai/utils': ImportsMap;
recoil: ImportsMap;
'@vue/composition-api': unimport.InlinePreset;
pinia: unimport.InlinePreset;
'vue-demi': unimport.InlinePreset;
'vue-i18n': unimport.InlinePreset;
'vue-router-composables': unimport.InlinePreset;
vue: unimport.InlinePreset;
'vue/macros': unimport.InlinePreset;
vitest: unimport.InlinePreset;
rxjs: unimport.InlinePreset;
'date-fns': unimport.InlinePreset;
};
type PresetName = keyof typeof presets;
interface ImportLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportExtended extends Import {
sideEffects?: SideEffectsInfo;
__source?: 'dir' | 'resolver';
}
type ImportNameAlias = [string, string];
type SideEffectsInfo = Arrayable<ResolverResult | string> | undefined;
interface ResolverResult {
as?: string;
name?: string;
from: string;
}
type ResolverFunction = (name: string) => Awaitable<string | ResolverResult | ImportExtended | null | undefined | void>;
interface ResolverResultObject {
type: 'component' | 'directive';
resolve: ResolverFunction;
}
/**
* Given a identifier name, returns the import path or an import object
*/
type Resolver = ResolverFunction | ResolverResultObject;
/**
* module, name, alias
*/
type ImportsMap = Record<string, (string | ImportNameAlias)[]>;
interface ScanDirExportsOptions {
/**
* Register type exports
*
* @default true
*/
types?: boolean;
}
/**
* Directory to search for import
*/
interface ScanDir {
glob: string;
types?: boolean;
}
type NormalizedScanDir = Required<ScanDir>;
type ESLintGlobalsPropValue = boolean | 'readonly' | 'readable' | 'writable' | 'writeable';
interface ESLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
/**
* @default true
*/
globalsPropValue?: ESLintGlobalsPropValue;
}
interface BiomeLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
}
interface Options {
/**
* Preset names or custom imports map
*
* @default []
*/
imports?: Arrayable<ImportsMap | PresetName | InlinePreset>;
/**
* Local package presets.
*
* Register local installed packages as a preset.
*
* @default []
* @see https://github.com/unplugin/unplugin-auto-import#package-presets
*/
packagePresets?: (PackagePreset | string)[];
/**
* Identifiers to be ignored
*/
ignore?: (string | RegExp)[];
/**
* These identifiers won't be put on the DTS file
*/
ignoreDts?: (string | RegExp)[];
/**
* Inject the imports at the end of other imports
*
* @default true
*/
injectAtEnd?: boolean;
/**
* Options for scanning directories for auto import
*/
dirsScanOptions?: ScanDirExportsOptions;
/**
* Path for directories to be auto imported
*/
dirs?: (string | ScanDir)[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: Arrayable<Arrayable<Resolver>>;
/**
* Parser to be used for parsing the source code.
*
* @see https://github.com/unjs/unimport#acorn-parser
* @default 'regex'
*/
parser?: UnimportOptions['parser'];
/**
* Filepath to generate corresponding .d.ts file.
* Default enabled when `typescript` is installed locally.
* Set `false` to disable.
*
* @default './auto-imports.d.ts'
*/
dts?: string | boolean;
/**
* Auto import inside Vue templates
*
* @see https://github.com/unjs/unimport/pull/15
* @see https://github.com/unjs/unimport/pull/72
* @default false
*/
vueTemplate?: boolean;
/**
* Enable auto import directives for Vue's SFC.
*
* Library authors should include `meta.vueDirective: true` in the import metadata.
*
* When using a local directives folder, provide the `isDirective`
* callback to check if the import is a Vue directive.
*
* @see https://github.com/unjs/unimport?tab=readme-ov-file#vue-directives-auto-import-and-typescript-declaration-generation
*/
vueDirectives?: true | AddonVueDirectivesOptions;
/**
* Set default export alias by file name
*
* @default false
*/
defaultExportByFilename?: boolean;
/**
* Rules to include transforming target.
*
* @default [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/]
*/
include?: FilterPattern;
/**
* Rules to exclude transforming target.
*
* @default [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
*/
exclude?: FilterPattern;
/**
* Generate corresponding .eslintrc-auto-import.json file.
*/
eslintrc?: ESLintrc;
/**
* Generate corresponding .biomelintrc.json file.
*/
biomelintrc?: BiomeLintrc;
/**
* Save unimport items into a JSON file for other tools to consume.
* Provide a filepath to save the JSON file.
*
* When set to `true`, it will save to `./.unimport-items.json`
*
* @default false
*/
dumpUnimportItems?: boolean | string;
/**
* Include auto-imported packages in Vite's `optimizeDeps` option
*
* @default true
*/
viteOptimizeDeps?: boolean;
}
export type { BiomeLintrc, ESLintGlobalsPropValue, ESLintrc, ImportExtended, ImportLegacy, ImportNameAlias, ImportsMap, NormalizedScanDir, Options, PresetName, Resolver, ResolverFunction, ResolverResult, ResolverResultObject, ScanDir, ScanDirExportsOptions, SideEffectsInfo };
@@ -0,0 +1 @@
import "./chunk-DTT25XJ5.js";
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/vite.ts
var vite_default = _chunkA6NGEVNDcjs.unplugin_default.vite;
exports.default = vite_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/vite.ts
var vite_default = unplugin_default.vite;
export {
vite_default as default
};
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/webpack.ts
var webpack_default = _chunkA6NGEVNDcjs.unplugin_default.webpack;
exports.default = webpack_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/webpack.ts
var webpack_default = unplugin_default.webpack;
export {
webpack_default as default
};
@@ -0,0 +1,194 @@
{
"name": "unplugin-auto-import",
"type": "module",
"version": "19.1.0",
"description": "Register global imports on demand for Vite and Webpack",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/unplugin/unplugin-auto-import#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/unplugin/unplugin-auto-import.git"
},
"bugs": {
"url": "https://github.com/unplugin/unplugin-auto-import/issues"
},
"keywords": [
"unplugin",
"vite",
"astro",
"webpack",
"rollup",
"rspack",
"auto-import",
"transform"
],
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./nuxt": {
"import": {
"types": "./dist/nuxt.d.ts",
"default": "./dist/nuxt.js"
},
"require": {
"types": "./dist/nuxt.d.cts",
"default": "./dist/nuxt.cjs"
}
},
"./astro": {
"import": {
"types": "./dist/astro.d.ts",
"default": "./dist/astro.js"
},
"require": {
"types": "./dist/astro.d.cts",
"default": "./dist/astro.cjs"
}
},
"./rollup": {
"import": {
"types": "./dist/rollup.d.ts",
"default": "./dist/rollup.js"
},
"require": {
"types": "./dist/rollup.d.cts",
"default": "./dist/rollup.cjs"
}
},
"./types": {
"import": {
"types": "./dist/types.d.ts",
"default": "./dist/types.js"
},
"require": {
"types": "./dist/types.d.cts",
"default": "./dist/types.cjs"
}
},
"./vite": {
"import": {
"types": "./dist/vite.d.ts",
"default": "./dist/vite.js"
},
"require": {
"types": "./dist/vite.d.cts",
"default": "./dist/vite.cjs"
}
},
"./webpack": {
"import": {
"types": "./dist/webpack.d.ts",
"default": "./dist/webpack.js"
},
"require": {
"types": "./dist/webpack.d.cts",
"default": "./dist/webpack.cjs"
}
},
"./rspack": {
"import": {
"types": "./dist/rspack.d.ts",
"default": "./dist/rspack.js"
},
"require": {
"types": "./dist/rspack.d.cts",
"default": "./dist/rspack.cjs"
}
},
"./esbuild": {
"import": {
"types": "./dist/esbuild.d.ts",
"default": "./dist/esbuild.js"
},
"require": {
"types": "./dist/esbuild.d.cts",
"default": "./dist/esbuild.cjs"
}
},
"./*": "./*"
},
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"typesVersions": {
"*": {
"*": [
"./dist/*",
"./*"
]
}
},
"files": [
"*.d.ts",
"dist"
],
"engines": {
"node": ">=14"
},
"peerDependencies": {
"@nuxt/kit": "^3.2.2",
"@vueuse/core": "*"
},
"peerDependenciesMeta": {
"@nuxt/kit": {
"optional": true
},
"@vueuse/core": {
"optional": true
}
},
"dependencies": {
"local-pkg": "^1.0.0",
"magic-string": "^0.30.17",
"picomatch": "^4.0.2",
"unimport": "^4.1.1",
"unplugin": "^2.2.0",
"unplugin-utils": "^0.2.4"
},
"devDependencies": {
"@antfu/eslint-config": "^4.2.0",
"@antfu/ni": "^23.3.1",
"@antfu/utils": "^9.0.0",
"@nuxt/kit": "^3.15.4",
"@nuxt/schema": "^3.15.4",
"@svgr/plugin-jsx": "^8.1.0",
"@types/node": "^22.13.4",
"@types/picomatch": "^3.0.2",
"@types/resolve": "^1.20.6",
"@vueuse/metadata": "^12.6.1",
"bumpp": "^10.0.3",
"eslint": "^9.20.1",
"esno": "^4.8.0",
"fast-glob": "^3.3.3",
"publint": "^0.3.5",
"rollup": "^4.34.7",
"tsup": "^8.3.6",
"typescript": "^5.7.3",
"vite": "^6.1.0",
"vitest": "^3.0.5",
"webpack": "^5.98.0"
},
"scripts": {
"build": "tsup src/*.ts --format cjs,esm --dts --splitting --clean",
"dev": "tsup src/*.ts --watch src",
"lint": "eslint .",
"lint:fix": "nr lint --fix",
"typecheck": "tsc",
"play": "npm -C playground run dev",
"release": "bumpp && pnpm publish",
"start": "esno src/index.ts",
"test": "vitest",
"test:run": "vitest run"
}
}