Skip to content

介绍

自动导入, 不再需要手动导入, 更多信息请看这里

配置

js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import { resolve as resolvePath } from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolvePath('./src'),
    },
  },
  plugins: [
    vue(),
    AutoImport({
      include: [
        // 哪些文件需要自动导入?
        /\.[tj]sx?$/,
        /\.vue$/,
        /\.vue\?vue/,
        /\.md$/,
      ],
      imports: [
        // 1. 使用插件默认的自动导入预设, 支持哪些预设? 请看这里:
        // https://github.com/unplugin/unplugin-auto-import/tree/main/src/presets
        'vue',

        // 2.自定义自动导入
        {
          axios: [
            ['default', 'axios'], // 自动导入 axios
          ],

          // 导入格式如下:
          // "[package-name]": [
          //   "[import-names]",
          //   ["[from]", "[alias]"],
          // ],


          // 2.1 自动导入类型
          {
            from: 'vue-router',
            imports: ['RouteLocationRaw'],
            type: true,
          },
          dts: true,

          // 2.3 禁止 eslint 检测报错
          eslintrc: {
            enabled: false,
            // filepath: './.eslintrc-auto-import.json',
            globalsPropValue: true,
          },
        },
      ],
    }),
  ],
});

最后

不要自动导入太多东西, 只将一些特别常用的库设置为自动导入即可(如: vue composition api), 因为这种的一看就知道这个API是做什么用的, 如果滥用这个插件, 就会导致看代码的时候不知道方法是从哪里来的, 还需要去看配置文件

Released under the MIT License.