Auto import APIs on-demand for Vite, Webpack, Rollup and esbuild

Last update: Jul 5, 2022

unplugin-auto-import

NPM version

Auto import APIs on-demand for Vite, Webpack, Rollup and esbuild. With TypeScript support. Powered by 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>
}

Install

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

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

Example: playground/


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

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


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


Nuxt
// nuxt.config.js
export default {
  buildModules: [
    ['unplugin-auto-import/nuxt', { /* options */ }],
  ],
}

This module works for both Nuxt 2 and Nuxt Vite


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


Quasar
// quasar.conf.js
const AutoImportPlugin = require('unplugin-auto-import/webpack')

module.exports = {
  build: {
    chainWebpack(chain) {
      chain.plugin('unplugin-auto-import').use(
        AutoImportPlugin({ /* options */ }),
      )
    },
  },
}


esbuild
// esbuild.config.js
import { build } from 'esbuild'

build({
  /* ... */
  plugins: [
    require('unplugin-auto-import/esbuild')({
      /* options */
    }),
  ],
})


Configuration

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]'],
      ],
    },
  ],

  // 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`
    filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
    globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
  },

  // custom resolvers
  // see https://github.com/antfu/unplugin-auto-import/pull/23/
  resolvers: [
    /* ... */
  ],

  // 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',
})

Refer to the type definitions for more options.

Presets

See src/presets.

ESLint - eslint(no-undef)

Configure options.eslintrc, and modify your eslint configuration file.

Example:

// .eslintrc.js

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

ESLint Docs: Extending Configuration Files

Note: .eslintrc-auto-import.json is generated automatically, If the configuration file changes do not take effect in time, please check the configuration file, restart eslint server or the editor

TypeScript

In order to properly hint types for auto-imported APIs, make sure:

  • to configure options.dts so that auto-imports.d.ts file is automatically generated
  • to include auto-imports.d.ts in tsconfig.json

FAQ

Compare to 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

License

MIT License © 2021 Anthony Fu

GitHub

https://github.com/antfu/unplugin-auto-import
Comments
  • 1. Bundle size increases with the plugin when used in a quasar project

    Hii @antfu, When a normal build is done on a quasar project, the build bundle size is 500kb smaller than a build with the plugin used.

    Steps to reproduce

    • create a new quasar cli project
    • do a normal build
    • check dist/spa folder size
    • install unplugin-auto-import
    • add it in quasar config with the following presets installed
     chainWebpack(chain) {
            chain.plugin('unplugin-auto-import').use(
              AutoImportPlugin({
                // 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',
                  'vuex',
                  'quasar',
                ],
              })
            );
          },
    
    • remove all vue API imports and run a build
    • check dist/spa folder size
    • it's higher than that of the normal build

    What's expected

    • The bundle size should remain the same because we have Tree shaking in place

    What happenes

    • The bundle size with the plugin is larger than without the plugin

    Please let me know if you need a repo to reproduce. I did it with a project with around 20 .vue files and 10 plus .ts files

    Reviewed by soulsam480 at 2021-10-26 16:17
  • 2. ref is not defined for production build

    works fine in development mode, but in production build with npm run build, it shows ‘ref is not defined’

    <template>
      <div ref="divRef">test</div>
    </template>
    
    <script setup>
    const divRef = ref(null);
    </script>
    
    <style scoped></style>
    
    Reviewed by mlhou at 2021-11-29 01:37
  • 3. [Bug] shipped `.mjs` bundle includes reference to `__dirname`

    __dirname is not available in ES modules. Had to switch my project to ESM for another dependency and this came up as an error. I'm not clear on how files are handled, but maybe it's not respecting the

    "exports": {
        ".": {
          "import": "./index.mjs",
          "require": "./index.cjs"
        },
        "./*": "./*"
      },
    

    from the package.json of auto-imported modules

    Reviewed by josh-hemphill at 2021-11-23 03:38
  • 4. stuck infinite loading loop with vitesse-like setup starting from v0.6.x

    I upgraded to v0.6.0/0.6.1 and now when loading a page in development, the app is constantly reloading. I see this this in console:

    image

    and the counter (x185) continues to go up. Previous versions (v0.5.11) are fine.

    Reviewed by wc-matteo at 2022-02-28 09:19
  • 5. 之前使用版本 0.7.1 升级0.8.5版本之后编译报错 Cannot read properties of null (reading 'startsWith')

    \node_modules\unplugin-auto-import\node_modules\unplugin\dist\webpack\loaders\transform.js??ref--39-0!***\node_modules\unplugin-vue-components\node_modules\unplugin\dist\webpack\loaders\transform.js??ref--40-0!***\node_modules\unplugin-auto-import\node_modules\unplugin\dist\webpack\loaders\transform.js??ref--39-0\node_modules\unplugin-vue-components\node_modules\unplugin\dist\webpack\loaders\transform.js??ref--40-0!***\node_modules\cache-loader\dist\cjs.js??ref--13-0!***\node_modules\babel-loader\lib\index.js!***\node_modules\cache-loader\dist\cjs.js??ref--1-0!***\node_modules\vue-loader-v16\dist\index.js??ref--1-1!*** Cannot read properties of null (reading 'startsWith')

    Reviewed by wowoName at 2022-05-30 09:48
  • 6. Duplicate imports when using `import as` syntax.

    2022-02-15_05-41 The content transformed by @vitejs/plugin-vue imported defineComponent from vue and renamed it to _defineComponent. Ideally, auto-import will not transform it. But the fact is that it will.

    Reviewed by Zolyn at 2022-02-15 00:22
  • 7. How to use with Jest ?

    version: 0.4.5

    // MyComponent.tsx
    export default defineComponent({
        // ....
    })
    
    // *.spec.ts
    it('should render', () => {
        const wrapper = shallowMount(MyComponent)  // throw error: defineComponent is not defined
    })
    
    Reviewed by Hyphon at 2021-09-13 07:50
  • 8. ESLint errors

    I tried to use this plugin for vue-use and now I receive such eslint errors:

    ESLint: 'useVModel' is not defined.(no-undef)
    

    Maybe you can create something like https://github.com/antfu/vue-global-api#eslint

    Reviewed by Djaler at 2021-08-24 11:37
  • 9. 配置 'vue/macros' 后浏览器报错,does not provide an export named '$'

    does not provide an export named '$' (at validates.ts:10:8)

    vite.config.js

    plugins: [
    vue({
            reactivityTransform: true,
          }),
     AutoImport({
            imports: [
              'vue',
              'vue/macros',
              'vue-router',
              '@vueuse/core',
            ],
            dts: 'src/types/auto-import.d.ts',
          }),
    ]
    
    

    validates.ts ↓

    export function isExternal(path: string): boolean {
      return /^(https?:|mailto:|tel:)/.test(path)
    }
    
    export function validPassword(password: string): boolean {
      return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9-*/[email protected]#$%^&*()]{8,20}$/.test(password)
    }
    

    在配置 'vue/macros 之前是可用的

    Reviewed by wangping1511 at 2022-05-14 16:06
  • 10. Values in vue templates don't trigger auto-import

    If looking at the template itself isn't a good idea, perhaps some dev-facing comment directives or config options to set more limited matching for specific use cases could be helpful.

    To give an example. I can do the following, but I have to add the variable names to something in the script block for it to work, which kind of defeats the purpose.

    AutoImport({
    	imports: [
    		'vue',
                    {
                    	'@mdi/js': Object.keys(await import('@mdi/js')).filter(v=>v.startsWith('mdi')),
                    }
    	],
    }),
    
    <script setup lang="ts">
    // Ideally I wouldn't end up with having to write out import statements with 12+ different variables
    // but to get them to auto-import, I've got to do something like this:
    const i = {mdiInformationOutline}
    
    // And I can't just do `import * as i from '@mdi/js'` because then it doesn't get tree shook, and I end up with 2MB+ file
    </script>
    <template>
      <main class="px-4 py-10 text-center text-teal-700 dark:text-gray-200">
        <div>
          <p class="text-4xl">
            <v-icon :icon="i.mdiInformationOutline" class="inline-block" />
          </p>
        </div>
        <router-view />
      </main>
    </template>
    
    Reviewed by josh-hemphill at 2022-01-22 11:10
  • 11. 自动注册vue无效

    VUE CLI (4.5.15) vue.config.js

    const AutoImport = require('unplugin-auto-import/webpack')
    const Components = require('unplugin-vue-components/webpack')
    const Icons = require('unplugin-icons/webpack')
    const IconsResolver = require('unplugin-icons/resolver')
    const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
    
    module.exports = {
         configureWebpack: {
            plugins: [
                AutoImport({
                    imports: ['vue', 'vue-router'],
                    resolvers: [ElementPlusResolver()]
                }),
                Components({
                    resolvers: [
                        ElementPlusResolver(),
                        IconsResolver({
                            prefix: false,
                            enabledCollections: ['ep']
                        })
                    ]
                }),
                Icons({
                    autoInstall: true
                })
            ]
        }
    }
    

    App.vue

    <template>
      <el-config-provider :locale="locale" :button="button">
        <el-container>
          <Header />
          <el-container>
            <Sidebar />
            <Main />
          </el-container>
        </el-container>
      </el-config-provider>
    </template>
    
    <script>
    import zhCN from "element-plus/lib/locale/lang/zh-cn";
    
    export default defineComponent({
      name: "App",
      components: {},
      setup() {
        const locale = ref(zhCN);
        const button = reactive({
          autoInsertSpace: true,
        });
    
        return {
          locale,
          button,
        };
      },
    });
    </script>
    

    会提示: defineComponent ref reactive 未定义

    Reviewed by cuiqg at 2021-12-22 13:04
  • 12. Suggest: I think we can count on community to add d.ts preset is a better idea.

    When use this plugin in typescript, the most import thing is to define d.ts from some lib. But for developers, finding the corresponding type definitions in the d.ts file is undoubtedly a mental burden. You may say we can do like this

    export {}
    delcalare global {
        const watch: typeof import('vue')['watch']
    }
    

    However, for some ides such as webstorm, it will highlight watch as a variable rather than a function, which is very uncomfortable visually. Therefore, the best way is to copy the corresponding type definitions in the corresponding repo

    This is an example for react

    /**
       * Returns a stateful value, and a function to update it.
       *
       * @version 16.8.0
       * @see https://reactjs.org/docs/hooks-reference.html#usestate
       */
      function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]
      // convenience overload when first argument is omitted
      /**
       * Returns a stateful value, and a function to update it.
       *
       * @version 16.8.0
       * @see https://reactjs.org/docs/hooks-reference.html#usestate
       */
      function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>]
    

    thus we can get more powerful intellisense.

    Would you consider doing so

    Reviewed by SnowingFox at 2022-06-27 02:17
  • 13. 利用unplugin-auto-import引入组件,在修改文件热更新后进行重载导致样式丢失

    Element Plus version

    2.2.5

    OS/Browsers version

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

    unplugin-auto-import version

    0.8.7

    Reproduction Link

    https://github.com/Pudon/vue3-demo

    Steps to reproduce

    1. npm run dev
    2. 修改一点代码-热更新
    3. 浏览器点击重载
    4. 再点击显示消息-样式丢失
    Reviewed by Pudon at 2022-06-14 02:05
  • 14. Vue3 tsx auto import invalid

    vite.config.ts

    `import {fileURLToPath, URL} from 'url'

    import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import AutoImport from 'unplugin-auto-import/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import Components from 'unplugin-vue-components/vite' import IconsResolver from 'unplugin-icons/resolver' import Icons from 'unplugin-icons/vite' import ElementPlus from 'unplugin-element-plus/vite' export default defineConfig({ plugins: [ vue({reactivityTransform: true}), vueJsx(), AutoImport({ include: [ /.[tj]sx?$/, // .ts, .tsx, .js, .jsx /.vue$/, /.vue?vue/, // .vue /.md$/, // .md ], imports: ['vue', 'vue/macros','@vueuse/core'], dts: './auto-imports.d.ts', resolvers: [ ElementPlusResolver(), IconsResolver({ prefix: 'abc', enabledCollections: ['ep','mdi'], }), ], }), Components({ resolvers: [ IconsResolver({ prefix: 'abc', enabledCollections: ['ep','mdi'], }), ElementPlusResolver(), ], dts: './components.d.ts', }), ElementPlus({ // importStyle: 'sass', useSource: true }), Icons({ autoInstall: true, }), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, })`

    index.tsx

    import {ElMenu,ElMenuItem,ElSubMenu} from "element-plus" export default defineComponent({ components:{ // ElMenu,ElMenuItem,ElSubMenu }, props: { }, setup() { return () => { return ( <el-menu className="menu-icon-svg" > <abc-ep-close /> </el-menu> ) } } })

    icon auto import is also invalid

    Reviewed by zz541843 at 2022-06-04 15:34
  • 15. [Question] how to change eol of auto generated d.ts

    In my project, eol is set as 'crlf' in rule of prettier. However, each time I launch vite, eol in auto-import.d.ts is replaced with 'lf'. Is there a recommended way to solve this? As this file is the only one in ./src folder which is generated by a package, it seems not elegant to create prettier and eslint ignore file just for it. Maybe there is another way?

    Reviewed by kingyue737 at 2022-06-04 14:17
Extended version of vite's official vue-ts template. adds CI, linting, testing and auto-formatting.

vite-vue-ts-template extended version of vite's official vue-ts template. additional features: eslint for linting. vitest + testing-library for testin

Jun 1, 2022
My personal website. Base on Vite 2.0 and Vue 3.0. If you want to know how to use Vite to develop a project, you can refer to this repository.
My personal website. Base on Vite 2.0 and Vue 3.0. If you want to know how to use Vite to develop a project, you can refer to this repository.

chengpeiquan.com My personal website. Base on Vite 2.0 and Vue 3.0. You can see Rewrite in vite to learn more. Architecture License MIT License © 2021

Jun 29, 2022
Very low cost dynamic themes in vite and Ant Design Vue. About using @zougt/vite-plugin-theme-preprocessor.
Very low cost dynamic themes in vite and Ant Design Vue. About using @zougt/vite-plugin-theme-preprocessor.

Vite + ant-design-vue about dynamic themes demo https://gitofzgt.github.io/vite-dynamictheme-antd-vue-demo/ Using the plugin @zougt/vite-plugin-theme-

May 28, 2022
Vite-starter - Vueform Vite + TailwindCSS 3 Boilerplate
Vite-starter - Vueform Vite + TailwindCSS 3 Boilerplate

Vueform Vite + TailwindCSS 3 Boilerplate Last tested with Vite 2.7.13. Installat

Feb 8, 2022
Vue 3 boilerplate starter based on Vite and Tailwindcss 2
Vue 3 boilerplate starter based on Vite and Tailwindcss 2

vite-wind WIP ?? ?? ?? It's a Vue 3 boilerplate based on Tailwindcss + Typescript + Vite + css-pro-layout, You could clone this repository and use the

May 8, 2022
Vite - Vue 2 starter template using composition-api and windiCSS

Vite ⚡ - Vue 2 starter template Create a Vue 2 application bundled by the lightning fast build tool Vite ✨ Live Demo ?? Features ⚡️ Vite 2, Vue 2 and

Jun 30, 2022
Cypres component testing with Vue 3 and Vite

Cypress Vue 3 Vite Vite template with Vue 3 and Cypress component testing. Clone the repository and run yarn install to install the dependencies. yarn

May 16, 2022
This template should help get you started developing with Vue 3 and Typescript in Vite.

Underscore_ Voici la homepage du podcast ! Vue 3 + Typescript + Vite This template should help get you started developing with Vue 3 and Typescript in

Mar 27, 2022
Starter template for Neutralino.js with Vite.js and Vue.js

Neutralino.js Template With Vite.js and Vue.js Neutralino.js Neutralino.js is a new competitor to Electron.js which is smaller and consumes tiny amoun

Jun 16, 2022
👻 A fast Simple Vite 2, Vue 3 and Electron 13.x template.
👻 A fast Simple Vite 2, Vue 3 and Electron 13.x template.

?? A fast Simple Vite 2, popular front-end frameworks and Electron 13.x template. This template should help get you started developing with Vite 2, popular front-end frameworks and Typescript in Electron.

Jun 1, 2022
A Vue.js template with built-in Vite, Sass, TypeScript, PostCSS, and Tailwind CSS to help you start your project!

Vue 3 + Typescript + Vite This template should help get you started developing with Vue 3 and Typescript in Vite. The template uses Vue 3 <script setu

Jun 15, 2022
My ⚡️Vite configuration, including ESLint, Prettier and Tailwind CSS

Install and configure ESLint, Prettier, and Tailwind CSS using Vite (in VS Code) The First Step Create a new Vite project through yarn: yarn create vi

Dec 12, 2021
Testing out vite with laravel, vue and inertia

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Dec 25, 2021
Emp-portal-vite - A template with Vue Router, VueX, TailwindCss and JIT Compiler
Emp-portal-vite - A template with Vue Router, VueX, TailwindCss and JIT Compiler

Vite + Vue + VueX + Vue Router + TailwindCss + JIT This template allows you to q

Jan 29, 2022
Open source Wordle clone built with Vue, TypeScript, and Vite

Vue 3 + Typescript + Vite This template should help get you started developing with Vue 3 and Typescript in Vite. The template uses Vue 3 <script setu

May 15, 2022
🏕 Opinionated Vite Starter Template
🏕 Opinionated Vite Starter Template

Mocking up web app with Vitesse(speed) Now with Windi CSS! ⚡️ Live Demo Features ⚡️ Vue 3, Vite 2, pnpm, ESBuild - born with fastness ?? File based ro

Jun 27, 2022
Vite 2.x + Vue 3.x + Tailwind 2.x (starter) ⚡

Vite 2.x + Vue 3.x + Tailwind 2.x starter ⚡ This starter template also includes: Vue Router 4.x Inter var font (self-hosted, woff2 format, version 3.1

Jun 26, 2022
Opinionated Vite + Vue 3 + TypeScript + Tailwind CSS starter.

Vite Typescript + Tailwind Starter Simple, opinionated, and production-ready TS + Tailwind project template for Vite 2. See changelog for latest chang

Jun 21, 2022
Electron app boilerplate based on Vite 2.0

Vite Electron Builder Template Vite+Electron = ?? This is a secure template for electron applications. Written following the latest safety requirement

Jul 4, 2022