vite-plugin-import

raw JSON →
0.4.0 verified Mon Apr 27 auth: no javascript

Component modular import plugin for Vite (v0.4.0, last updated 2021). Converts named imports like `import { Button } from 'antd'` into path-level imports (e.g., `antd/lib/button`) to reduce bundle size, leveraging babel-plugin-import under the hood. Works primarily in build mode by default. Requires Vite 2. Note that tree-shakable libraries (like antd) do not need this plugin, as Vite handles unused code removal. Faster than combining `@rollup/plugin-babel` with babel-plugin-import, but limited to import transformation only.

error Error: Cannot find module 'vite-plugin-import'
cause Package not installed or missing from dependencies.
fix
Run npm install vite-plugin-import --save-dev.
error TypeError: createImportPlugin is not a function
cause Importing as named export instead of default export.
fix
Use import createImportPlugin from 'vite-plugin-import' (no curly braces).
error Error: The node module 'vite' is not a peer dependency of 'vite-plugin-import'.
cause Missing Vite peer dependency.
fix
Install Vite 2.x: npm install vite@2.
error Error: Cannot find module 'babel-plugin-import'
cause vite-plugin-import uses babel internally; if babel-plugin-import is missing, this error may appear.
fix
Install babel-plugin-import: npm install babel-plugin-import --save-dev.
gotcha Plugin only works effectively in build mode by default (onlyBuild: true). During dev (vite serve), imports are not transformed, which may lead to inconsistency if you rely on side-effects from style imports.
fix Set `onlyBuild: false` in plugin options to enable transformation in both dev and build modes.
gotcha vite-plugin-import is essentially a wrapper around babel + babel-plugin-import. It does not support other babel plugins; use @rollup/plugin-babel if you need additional babel transforms.
fix Use @rollup/plugin-babel + babel-plugin-import instead for custom babel configuration.
gotcha Tree-shakable libraries (e.g., antd v4+) do not benefit from this plugin because Vite already eliminates unused exports during build. Unnecessary transformation may even increase build time.
fix Omit the plugin for tree-shakable libraries; verify with a bundle analyzer.
breaking Requires Vite 2; incompatible with Vite 3+.
fix Stay on Vite 2 or switch to alternative (e.g., unplugin-auto-import or manual imports).
npm install vite-plugin-import
yarn add vite-plugin-import
pnpm add vite-plugin-import

Shows how to configure vite-plugin-import to transform antd imports. The plugin converts named imports to path-level imports and optionally injects style imports.

// vite.config.js
import createImportPlugin from 'vite-plugin-import';

export default {
  plugins: [
    createImportPlugin([
      {
        libraryName: 'antd',
        style: true, // or 'css'
      },
    ]),
  ],
};