ITADN
unplugin/unplugin-auto-import
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

unplugin-auto-import

NPM version

按需自动导入 Vite、Webpack、Rspack、Rollup 和 esbuild 的 API。支持 TypeScript。由 unplugin 提供支持。


without

import { computed, ref } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

with

const count = ref(0)
const doubled = computed(() => count.value * 2)

without

import { useState } from 'react'

export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

with

export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

安装

npm i -D unplugin-auto-import
Vite
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({ /* options */ }),
  ],
})

示例:playground/


Rollup
// rollup.config.js
import AutoImport from 'unplugin-auto-import/rollup'

export default {
  plugins: [
    AutoImport({ /* options */ }),
    // other plugins
  ],
}


Rolldown
// rolldown.config.js
import AutoImport from 'unplugin-auto-import/rolldown'

export default {
  plugins: [
    AutoImport({ /* options */ }),
    // other plugins
  ],
}


Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/webpack')({ /* options */ }),
  ],
}


Rspack
// rspack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/rspack')({ /* options */ }),
  ],
}


Nuxt

对于 Nuxt,你不需要此插件,它已内置。


Quasar
// vite.config.js [Vite]
import AutoImport from 'unplugin-auto-import/vite'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [
    AutoImport({ /* options */ })
  ]
})
// quasar.config.js
export default defineConfig(() => {
  return {
    build: {
      vitePlugins: [
        ['unplugin-auto-import/vite', { /* options */ }],
      ]
    },
  }
})


esbuild
// esbuild.config.js
import { build } from 'esbuild'
import AutoImport from 'unplugin-auto-import/esbuild'

build({
  /* ... */
  plugins: [
    AutoImport({
      /* options */
    }),
  ],
})


Astro
// astro.config.mjs
import AutoImport from 'unplugin-auto-import/astro'

export default defineConfig({
  integrations: [
    AutoImport({
      /* options */
    })
  ],
})


配置

AutoImport({
  // targets to transform
  include: [
    /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
    /\.vue$/,
    /\.vue\?vue/, // .vue
    /\.vue\.[tj]sx?\?vue/, // .vue (vue-loader with experimentalInlineMatchResource enabled)
    /\.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: {
    filePatterns: ['*.ts'], // Glob patterns for matching files
    fileFilter: file => file.endsWith('.ts'), // Filter files
    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',

  // The mode for generating the .d.ts file.
  // 'overwrite': overwrite the whole existing .d.ts file with the new type definitions.
  // 'append': only append the new type definitions to the existing .d.ts file, means the existing type definitions will be kept.
  // Default to 'append'
  dtsMode: 'append',

  // Preserve the original file extensions in the generated .d.ts file.
  // Set to `true` to keep the extensions for .ts and .tsx files.
  // Default to false
  dtsPreserveExts: false,

  // 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`
})

请参阅 类型定义 以获取更多选项。

预设

参见 src/presets

包预设

我们只为最流行的包提供预设,要使用此处未包含的任何包,你可以将其安装为 dev dependency 并将其添加到 packagePresets 数组选项中:

AutoImport({
  /* other options */
  packagePresets: ['detect-browser-es'/* other local package names */]
})

你可以查看 Svelte 示例 以获取一个可工作的示例,该示例注册了 detect-browser-es 包预设并在 App.svelte 中自动导入 detect 函数。

请参阅 unimport PackagePresets jsdocs 以获取有关 ignorecache 等选项的更多信息。

注意:确保使用的本地包已正确配置 package exports,否则相应的模块导出将不会被检测到。

TypeScript

为了正确提示自动导入的 API 的类型:

  1. 启用 options.dts,以便自动生成 auto-imports.d.ts 文件
  2. 确保 auto-imports.d.ts 未在 tsconfig.json 中被排除

AutoImport({
  dts: true // or a custom path
})

为了更好地支持使用自动导入 API 时的导航,请考虑使用 @dxup/unimport 包。

ESLint

💡 当使用 TypeScript 时,我们建议直接禁用 no-undef 规则,因为 TypeScript 已经会检查这些规则,你无需为此担心。

如果你遇到了 no-undef 的 ESLint 错误:

  1. 启用 eslintrc.enabled

AutoImport({
  eslintrc: {
    enabled: true, // <-- this
  },
})
  1. 更新您的 eslintrc扩展配置文件

// .eslintrc.js
module.exports = {
  extends: [
    './.eslintrc-auto-import.json',
  ],
}

常见问题

unimport 的比较

从 v0.8.0 开始,unplugin-auto-import 使用 unimport 作为底层。unimport 被设计为一个更底层的工具(它也曾为 Nuxt 的自动导入提供支持)。你可以将 unplugin-auto-import 视为它的一个封装,提供了更用户友好的配置 API 以及解析器等能力。今后,新功能的开发将主要发生在 unimport 中。

vue-global-api 的比较

你可以将此插件视为 vue-global-api 的继任者,但它提供了更多的灵活性,以及与 Vue 以外的库(例如 React)的绑定。

优点

  • 灵活且可定制
  • 支持 Tree-shaking(按需转换)
  • 无全局污染

缺点

  • 依赖构建工具集成(而 vue-global-api 是纯运行时)——不过,我们已经支持了其中许多!

赞助商

Sponsors

许可证

MIT 许可证 © 2021-PRESENT Anthony Fu