Implementation of Virtual File Introduced into Vite

  • 2021-11-13 00:32:24
  • OfStack

Directory background
Introducing virtual files
Example
Document
Typescript support
Summarize

Background

After upgrading vue3 in the new project, vue-cli will naturally be added & webpack has been replaced by vite. I have to say that vite is really fragrant, which not only has just compiled speed, but also has better support for the new functions of vue3.

However, I also encountered some problems in the development process

After seeing vite-plugin-pages After the plug-in, I suddenly saw this writing:


import routes from "virtual:generated-pages";

In fact, when using many vite plug-ins, I found that there is such a usage in references:


import xxx from "virtual:xxx";

So why hasn't this virtual: xxx been seen before? This is obviously not a package on npm. What would it be?

Introducing virtual files

After reading the document of vite, I realized that this is a function of introducing virtual files, which can generate a virtual file for you to introduce.

In the vite document plug-in API introduction of a virtual file said that this function, the chapter has written to support the introduction of you a virtual file, that is, this file does not exist, but through the code temporarily generated.

This generation is done by the plug-in of vite, that is to say, the corresponding virtual file is generated in nodejs environment

vite-plugin-pages is realized by this function. First, it traverses the corresponding page directory at compile time, and dynamically generates the corresponding routing table according to the naming rules of directory structure and file name, thus completing the good interaction between local directory structure and dynamic routing.

In fact, nuxt also has the function of dynamic routing, but it can not be introduced virtually. Before the project starts, it dynamically modifies webpack configuration and uses definePlugin to pass the routing table to the front-end code.

By introducing the function of virtual file, we avoid the need to pass the corresponding data to the front-end code by passing the modification constant.

In addition to passing constants, virtual introduction can do more, because it introduces a virtual js file, which means that we can also dynamically generate functions and code logic in it.

Example

For example, For example, we can automatically import the required files in the generated code, and then return a function to use the files imported before, so that we don't need to import these files in actual use, and we can directly use these files to be imported by returning the functions exported from virtual files.


import a from 'a-module'
import b from 'b-module'
...
import z from 'z-module'

const modules = {a,b,...,z}

export default useModule(name){
    return modules[name]
}

Previous use of


Related articles: