2

Vite Compared to Webpack is less difficult to get started, simple configuration, and out of the box. Although the current ecology is not as good as Webpack , the ecology is gradually enriched.

After some Vite plug-in writing practice, let's talk about virtual modules (Virtual Modules) today, and also introduce the vite-plugin-project-info plug-in by the way.

The concept of virtual modules

The virtual module is Vite Rollup virtual module of ---8ec9af4bf5a7584963652bbdc7aa0d38---, the virtual module is similar to alias alias, but the content of the module is not read directly from the disk, but compiled generate.

Virtual modules are a useful pattern that allows you to pass in some compile-time information to source files using ESM syntax.

Virtual module implementation example

First of all you may need to understand the API written by the plugin .

Here is an example of directly moving the official website:

 export default function myPlugin() {
  const virtualModuleId = 'virtual:my-module'
  const resolvedVirtualModuleId = '\0' + virtualModuleId

  return {
    name: 'my-plugin',
    resolveId(id) {
      if (id === virtualModuleId) {
        return resolvedVirtualModuleId
      }
    },
    load(id) {
      if (id === resolvedVirtualModuleId) {
        return `export const msg = "from virtual module"`
      }
    }
  }
}

Then import these modules into the code:

 import { msg } from 'virtual:my-module'

console.log(msg)

Practical Analysis: vite-plugin-project-info

vite-plugin-project-info is the Vite project information plug-in. After use, it will output the version, build time and other information in the Console panel.

Implementing plug-ins with virtual modules

  1. resolveId hook function: Convert the real virtual module ID to the internal virtual module ID.
  2. Load hook function: match the internal virtual module ID, and return the code at compile time, and finally implement the virtual:project-info module.
  3. transform hook function: realize automatic import function

    As of the second step, the function of the virtual module has been implemented, but we

 export default function projectInfoPlugin(opts: ProjectInfoPluginOptions = {}): PluginOption {
  const { entry = path.resolve('src/main'), locale } = opts;
  const lastEntry = entry.split('.')[0];
  const virtualModuleId = 'virtual:project-info';
  const resolvedVirtualModuleId = '\0' + virtualModuleId;

  return {
    name: 'vite:project-info',
    enforce: 'pre',
    resolveId(id) {
      if (id === virtualModuleId) {
        return resolvedVirtualModuleId;
      }
    },
    load(id) {
      if (id === resolvedVirtualModuleId) {
        return createCode({
          locale,
        });
      }
    },
    transform(code, id) {
      if (id.includes(path.resolve(lastEntry).replace(/\\/g, '/'))) {
        return {
          code: `import '${virtualModuleId}';\n${code}`,
          map: this.getCombinedSourcemap(),
        };
      }
    },
  };
}

function usage

Supports outputting relevant project information directly in the browser Console, and supports the use of the following codes:

 import projectInfo from 'virtual:project-info';
console.log(projectInfo.version); // 版本信息
console.log(projectInfo.buildTime); // 构建时间
console.log(projectInfo.name); // 项目名称
console.log(projectInfo.description); // 项目描述
console.log(projectInfo.repository); // 仓库链接
console.log(projectInfo.author); // 项目负责人或者作者

Samon
1.3k 声望92 粉丝