“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Hello, 🙎🏻♀️🙋🏻♀ 🙆🏻♀

I love knowledge transfer and am learning to write, ClyingDeng stool!

Vite working mechanism

When users request resources from Vite, a development server vite devServer is started inside vite. There is a working mechanism inside this server, which is equivalent to a pipeline (plug-in). Plug-ins are divided into system plug-ins (VUE) and user plug-ins. The user request must go through all the plug-ins to process it. This is a bit of a filter, middleware. The resources required by the request are processed, and the results of the transformation are returned to the user to get what the user wants.

Vite features: request a page, display the content of the page, no need to load and page irrelevant things. This means that future projects will load at the same speed no matter how big they are.

A plug-in can be an object or a function that contains the name of the plug-in and the associated hook function (to be executed at the time node where vite works).

The plugin hooks

General hook

Called when the server starts:

  • options
  • buildStart

Called on each incoming module request:

  • ResolveId creates a custom validation function, often used to locate third-party dependencies
  • Load creates a custom load function that returns custom content
  • transformThe transformation,Load in the code block further processing

Called when the server is down:

  • buildEnd
  • closeBundle

Vite avoids full AST parsing for performance. So there is no moduleParsed in development.

Vite unique hooks

Config: Modify the Vite configuration before it is parsed

ConfigResolved: called after the Vite configuration is resolved and confirmed

ConfigureServer: Hooks to configure the development server (custom middleware can be added)

TransformIndexHtml: Special hook for converting host page index.html

HandleHotUpdate: Performs custom HMR update processing

Initialize the plug-in process

1. Initialize the plugin:

Create the viet-plugin-example file (your own vite plugin)

The resolveId hook is used to take over a third party plug-in, so we can quickly determine if the third party plug-in is the one we need to handle. If so, take over, and then we can customize our own plug-in in the Load hook.

export default function (options) {
  return {
    name: 'dy-i18n'.resolveId(source) {
      // Whether to process the current request import the name of the plug-in in main
      if (source === 'dy-i18n') {
        return source // Indicates takeover
      }
      return null
    },
    load(id) {
      console.log('id', id)
      // Return the loaded thing
      return 'export default "this is virtaul"'}}},Copy the code

2. Configure the execution plug-in

In the viet.config.js file, execute the relevant plug-in functions

import i18n from './plugins/vite-plugin-example'
export default defineConfig({
    // Execute function i18n
  plugins: [vue(), i18n()],
})
Copy the code

3. Import in the import file

import dyI18n from 'dy-i18n'
// Use plugins
Copy the code

I18n plug-in

Initialize the project

Create a project using Vite, and then run the project. The on-demand loading of files is visible on the console.

Parse app file with a string of characters:

? : Indicates the SFC file of the file.

Type: The parsed module type is the style style file,

Index: follows the ordinal number and parses the first style of the current type

Lang. CSS: The parse language is CSS and the same is true for lang.i18n

Write i18N custom block

Here, we write the i18N plug-in to parse the custom module and return the code snippet that the user needs through the plug-in.

<i18n> { "en": { "language": "Language", "hello": "hello, world!" }, "en ": {"language": "language", "hello":" Hello world!" } } </i18n>Copy the code

When writing, you can find that the console reported an error. Our custom code block was not recognized.

This requires us to write a plug-in that handles the custom module and returns what is needed to the user.

Create a plug-in file

The next thing we need to do is take the code block and transform it.

Create a new plug-in file called vite-plugin-i18n.js.

export default {
  // code is the contents of the block
  // id is the requested URL
  transform(code, id) {
    // i18N information is written to the component configuration
    // Receive vUE file of type I18N
    if (!/vue&type=i18n/.test(id)) {
      return;
    }
    // The matching success export function (factory function) adds the contents of the i18N configuration options to the component as a block
    return `export default Comp => {
      Comp.i18n = ${code}} `; }};Copy the code

The request passes through the i18N plug-in and returns the resource that the plug-in handled. At this point, we can see in the console that the i18 custom block has been processed by the plug-in to add i18N properties to the component.

Language selector

In a vue file, write a static page of your language choice:

<template>
  <label>{{ t('language') }}</label>
  <select v-model="locale">
    <option value="en">en</option>
    <option value="zh">zh</option>
  </select>
  <p>{{ t('hello') }}</p>
</template>
Copy the code

The use of plug-in

Write the logic in script, get the code block in the i18N component instance, write the T function, return the field attribute value of the corresponding language. Determines the language based on locale, and retrieves the corresponding language value based on the key value attribute passed in.

const ins = getCurrentInstance()
function useI18n(){
    const locale = ref('zh')
    const i18n = ins.type.i18n
    const t = msg= > computed(() = > i18[locale.value][msg]).value
    return {locale,t}
}
const {locale,t} = useI18n()
Copy the code

You can see that it looks like this:

Perfect implementation, there should be applause here! 🎉 🎉 🎉

One item for those interested can be plus-one item for vite or just one item from the author (●’◡’●)! . If not, please give me your advice.