preface

In the previous project, in order to avoid the project packaging volume is too large, components that are not used globally need to be introduced on demand, ICONS used also need to be introduced manually on demand, constantly handwritten import, to be honest, this is very troublesome!

This is not, recently learned several brand new plug-ins, collate written share.

  • Do you get tired of using it every timevueWhen,Additional import vue apis are required
  • Do you get tired of using it every timeComponent libraryWhen,Additional on-demand import components are required
  • Are you tired of using it sometimesThird-party Component LibraryWhen,Additional CSS styles need to be introduced
  • Do you get tired of using it every timeiconWhen,Additional imports are required

There are several plugins that can help us solve these problems once and for all. We can use them without import when we call them, and when we package them, only the apis and components we actually use are built into the final product

Unplugin-auto-import: automatically introduce vue\vue-router\pinia, etc. apis on demand

Unplugin-vue-components: Automatically introduce third-party component library components and our own custom components on demand

Unplugin-icons: The ICONS used can be automatically imported on demand without manual import

Viet-plugin-style-import: Automatically imports, on demand, the CSS styles of the components we imported manually

I have here configuration sample code, to Element Plus and Ant Design Vue and Vite as an example, Webpack configuration can be viewed in the official repository configuration

The actual effect

As you can see, I don’t import the input component or vue’s REF API, but I still use it as usual

Automatically introduce apis, components, styles on demand

We’ll start by installing dependencies:

npm install -D unplugin-vue-components unplugin-auto-import
Copy the code

Then we configure vite.config.ts to add the following;

// vite.config.ts import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'; export default { plugins: [//... AutoImport({// you can also import pinia, vue-Router, vueuse, etc., // you can even use custom configuration rules, See https://github.com/antfu/unplugin-auto-import#configuration imports: [' vue '], / / parser resolvers third-party component libraries: [ElementPlusResolver()],}), Components({// dirs specifies the location of the component, default SRC/Components // allows us to use our own Components without the trouble of importing dirs: [' SRC /components/'], // the configuration needs to automatically import files with extensions as needed: ['vue', 'md'], // Parse the UI component library, here using Element Plus and Ant Design vue as examples: [ElementPlusResolver(), AntDesignVueResolver()], }), ], }Copy the code

Automatic import styles on demand for non-template components

Since the official release of Element Plus, there have been no on-demand import failures in the current Use of Element Plus on Vite2 + VUe3 +

What is a non-template component? Unplugin-vue-components does not currently scan components that are not used in templates, such as ant-Design-Vue’s Message component

We currently use ant-design-Vue’s Message component on demand, which we import manually:

<script setup lang="ts"> import { message } from 'ant-design-vue'; message.info('This is a normal message'); </script> Copies the codeCopy the code

Let’s see what happens in practice

As you can see in the image above, there is no CSS style. We have to manually import its CSS style, but this behavior is cumbersome, and a plugin was created to address this need:

Viet-plugin-style-import: automatically imports the style used by the third-party component library

Install the configuration

Here we take ant-design-vue as an example:

We’ll start by installing dependencies:

npm install -D vite-plugin-style-import
Copy the code

configuration

// vite.config.ts
import styleImport, { AndDesignVueResolve } from 'vite-plugin-style-import';

export default {
  plugins: [
    // ...
    styleImport({
      resolves: [AndDesignVueResolve()],
    }),
  ],
}
Copy the code

After this configuration, we manually import a component from the component library, and its style will be automatically loaded.

Automatically import ICONS on demand

We often struggle to find different ICONS, but now there is a great plugin and a great library to solve the problem of finding and using ICONS

Icones: is a very good icon library, which integrates many ICONS

Unplugin-icons: Automatically import the ICONS we want to use on demand, without manually importing them

Install the configuration
npm i -D unplugin-icons @iconify/json
Copy the code

Once installed, we configure vite.config.ts to add the following

// vite.config.ts
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'

export default {
  plugins: [
    Components({
      resolvers: IconsResolver(),
    }),
    Icons({
      compiler: 'vue3',
      autoInstall: true,
    }),
  ],
}
Copy the code
Use the sample

To start, go to icones.net lilify. app/ and choose an icon

And I’m gonna hit Copy

Going back to our code, just a short sentence is enough to use:

<template>
  <i-mdi-account-reactivate style="font-size: 2em; color: red" />
</template>
Copy the code

Start the optimization

After using these on-demand import plug-ins, we often see the following scenario for the first time when developing projects with Vite:

This can take a long time! For this situation, there are plug-ins to solve this problem

vite-plugin-optimize-persist

Install the configuration
npm i -D vite-plugin-optimize-persist vite-plugin-package-config
Copy the code

Edit the configuration vite.config.ts:

// vite.config.ts
import OptimizationPersist from 'vite-plugin-optimize-persist'
import PkgConfig from 'vite-plugin-package-config'

export default {
  plugins: [
    PkgConfig(),
    OptimizationPersist()
  ]
}
Copy the code

Once configured, the first time we use on-demand import, it will generate content in package.json (depending on what component your project is using), and the next time you come in, you can quickly run the project

TypeScript to red

After the first configuration, many people will find that the editor reports red for the components we introduced on demand:

This is because auto-imports. D. TS and components. D. TS files are generated in the project root directory by default.

The solution is simple:

  • Include both files in tsconfig.json
  • Configure the two.d.ts build directories in the SRC folder as follows
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

export default {
  plugins: [
    // ...
    AutoImport({
      dts: './src/auto-imports.d.ts',
    }),
    Components({
      dts: './src/components.d.ts'
    }),
  ],
}
Copy the code

Eslint to red

If we used Eslint in our project and used unplugin-auto-import, you would find this scenario

Yes, because Eslint can’t find the API we need to import, we don’t need import. Eslint doesn’t know that, so it gives us a red flag. Fine, since Eslint doesn’t know we’ve introduced the API on demand, shouldn’t we just let it know? Look at the code:

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

export default {
  plugins: [
    // ...
    AutoImport({
      // Generate corresponding .eslintrc-auto-import.json file.
      // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
      eslintrc: {
        enabled: true, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
    }),
  ],
}
Copy the code

Json file with all of the API names we introduced in it. Then we just need to load this file in.eslintrc.js

// .eslintrc.js

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

Complete usage example

For a complete example, see the template in another article: juejin.cn/post/705820…

I’m using Vite2 here