Vite introduces the implementation of virtual files

Vite introduces the implementation of virtual files

background

After upgrading vue3 in the new project, I naturally replaced vue-cli&webpack with vite. I have to say that vite is really good. Not only is the compilation speed just right, but it also has better support for the new features of vue3.

However, we encountered some problems during the development process.

After seeing vite-plugin-pages plugin, I suddenly saw this way of writing:

import routes from "virtual:generated-pages";

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

import xxx from "virtual:xxx";

So why haven't I seen this virtual:xxx before? This is obviously not a package on npm. What could it be?

Importing virtual files

After reading the vite documentation, I realized that this is a function to import virtual files. It can generate a virtual file for you to import.

This feature is mentioned in the section about introducing a virtual file in the plugin API of the vite document. It is written in the section that supports introducing a virtual file, that is, this file does not exist but is temporarily generated by code.

This generation is done through the vite plug-in, that is, to generate the corresponding virtual file in the nodejs environment

vite-plugin-pages is implemented through this function. It first traverses the corresponding page directory during compilation, and dynamically generates the corresponding routing table according to the directory structure and file name naming rules, thus completing the good interaction between the local directory structure and dynamic routing.

In fact, there is also a dynamic routing function in nuxt, but it does not have a virtual introduction. It dynamically modifies the webpack configuration before the project starts, and uses definePlugin to pass the routing table to the front-end code.

By introducing the function of virtual files, we avoid the need to pass the corresponding data to the front-end code by passing and modifying constants.

In addition to passing constants, virtual import can do more. You should know that it imports a virtual js file, which means that we can also dynamically generate functions and code logic in it.

example

For example, you can automatically import the required files in the generated code, and then return a function to use the previously imported files. In this way, we don't need to import these files in actual use. By returning the functions exported in the virtual file, we can directly use these files that were originally imported.

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]
}

Previously used 👇

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

a()
b()
c()

Use now 👇

import useModule from 'virtual:xxx'

const a = useModule('a')
const b = useModule('b')
const c = useModule('c')

Of course this is just a simple example, you can use your imagination to find more functions.

document

Let's go back to the document and see how the specific functions are implemented.

The example given in the document is as follows:

export default function myPlugin() {
  const virtualFileId = '@my-virtual-file'  

  return {
    name: 'my-plugin', // Required, will be displayed in warning and error resolveId(id) {
      if (id === virtualFileId) {
        return virtualFileId
      }
    },
    load(id) {
      if (id === virtualFileId) {
        return `export const msg = "from virtual file"`
      }
    }
  }
}

It can be seen that there are three main key points:

  • virtualFileId: The virtual file name to be introduced
  • resolveId(id): Determines whether it is a virtual file name that needs to be resolved
  • load(id): returns the code string of the corresponding virtual import file

It can be seen that the returned code is returned as a string. We can use template splicing or template translation to facilitate us to build the code string that needs to be returned.

Typescript support

However, it should be noted that the virtual file import returns js code instead of ts code, and the code is dynamically generated. This also means that we will encounter situations where there is no type support in TS during use.

If your code structure is certain, you can generate the corresponding d.ts definition file in advance. Then you can load the corresponding definition file by configuring compilerOptions.types in tsconfig. If the code structure is dynamic, you need to dynamically generate the corresponding d.ts file and write it into the project to implement it.

declare module 'virtual:xxx' {
...
}

Summarize

It can be seen that introducing virtual files is a very practical function. It not only allows the front-end code to interact with the compilation environment, but also dynamically generates code to implement some functions that were not so convenient to implement before. The specific implementation is also very simple to develop. Are you ready to use it in your plug-in?

This is the end of this article about the implementation of Vite introducing virtual files. For more information about Vite introducing virtual files, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Pros and Cons of Vite and Vue CLI
  • Detailed explanation of vite2.0+vue3 mobile project
  • Detailed explanation of vite+ts to quickly build vue3 projects and introduce related features
  • Detailed explanation of vite2.0 configuration learning (typescript version)
  • Steps to build the vite+vue3+element-plus project
  • Vue3.0+vite2 implements dynamic asynchronous component lazy loading
  • Implementation of vite+vue3.0+ts+element-plus to quickly build a project
  • Practice of using Vite2+Vue3 to render Markdown documents
  • Detailed explanation of the solution for migrating antd+react projects to vite

<<:  How to use Celery and Docker to handle periodic tasks in Django

>>:  Solve the problems encountered when installing MySQL 8.0 on Win10 system

Recommend

JS realizes special effects of web page navigation bar

This article shares with you a practical web navi...

Analysis of parameter transfer process of driver module in Linux

Declare the parameter name, type and permission y...

Nginx configures the same domain name to support both http and https access

Nginx is configured with the same domain name, wh...

How to make full use of multi-core CPU in node.js

Table of contents Overview How to make full use o...

How to decompress multiple files using the unzip command in Linux

Solution to the problem that there is no unzip co...

Reasons and solutions for the failure of React event throttling effect

Table of contents The problem here is: Solution 1...

How to check whether a port is occupied in LINUX

I have never been able to figure out whether the ...

How to change the dot in the WeChat applet swiper-dot into a slider

Table of contents background Target Effect Ideas ...

MySQL DATE_ADD and ADDDATE functions add a specified time interval to a date

MySQL DATE_ADD(date,INTERVAL expr type) and ADDDA...

About Docker security Docker-TLS encrypted communication issues

Table of contents 1. Security issues with Docker ...

Get the calculated style in the CSS element (after cascading/final style)

To obtain the calculated style in a CSS element (t...

Pure CSS and Flutter realize breathing light effect respectively (example code)

Last time, a very studious fan asked if it was po...

CSS achieves colorful and smart shadow effects

background Ever wondered how to create a shadow e...

Share JS four fun hacker background effect codes

Table of contents Example 1 Example 2 Example 3 E...