目标

实现React常用的组件自动引入(全局全量静态引入),Antd组件自动按需引入(按需部分动态引入)。

步骤

安装并配置unplugin-auto-import

安装unplugin-auto-import

npm i -D unplugin-auto-import

然后在vite.config.ts中引入该插件:

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'

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

然后根据需要在注释处进行配置,以下是我的配置:

AutoImport({
  // target to transform
  include: [
     /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
  ],

  imports: [
    'react',
    'react-router-dom',
    'ahooks'
  ],
}),

官方Vue配置示例:

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,

  // 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
    // ...
  ],

  // 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,

  // Custom resolvers, compatible with `unplugin-vue-components`
  // see https://github.com/antfu/unplugin-auto-import/pull/23/
  resolvers: [
    /* ... */
  ],

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

安装Antd和unplugin-auto-import-antd

npm install antd --save
npm i -D unplugin-auto-import-antd unplugin-auto-import

配置unplugin-auto-import-antd

在刚才的配置对象中添加以下配置:

// ...
import AntdResolver from 'unplugin-auto-import-antd'
// ...
    AutoImport({
        // ...
        resolvers: [AntdResolver()]
        // ...
    })
// ...

如果是webpack的话配置应该像这样:

// webpack.config.js
const AntdResolver = require('unplugin-auto-import-antd')

module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/webpack')({
      resolvers: [AntdResolver()]
    })
  ]
}

如果需要自定义前缀

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import AntdResolver from 'unplugin-auto-import-antd'

export default defineConfig({
  plugins: [
    AutoImport({
      resolvers: [
        AntdResolver({
          prefix: 'A'
        })
      ]
    })
  ]
})

如果需要包别名引入

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import AntdResolver from 'unplugin-auto-import-antd'

export default defineConfig({
  plugins: [
    AutoImport({
      resolvers: [
        AntdResolver({
          packageName: 'antd-v5'
        })
      ]
    })
  ]
})

等价于 import { Button } from 'antd-v5'

引入自动生成的声明文件

ts.config.json文件引入声明文件:

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "auto-imports.d.ts" // 此处引入该声明文件
  ],
  "references": [{ "path": "./tsconfig.node.json" }]
}

至此,大功告成。

参考资料


A Student on the way to full stack of Web3.