The simplest and most flexible way to build with a compiling magic 🪄
An Rsbuild plugin that allows you to create virtual modules, the pro version of rspack-plugin-virtual-module with loader API.
Install:
npm add rsbuild-plugin-virtual-module -DAdd plugin to your rsbuild.config.ts:
// rsbuild.config.ts
import { pluginVirtualModule } from 'rsbuild-plugin-virtual-module';
export default {
plugins: [
pluginVirtualModule({
virtualModules: {
'virtual-foo': async () => {
return 'export default {}';
},
},
}),
],
};import foo from 'virtual-foo';
console.log(foo); // {}Generate virtual modules, where the key is the name of the virtual module and the value is TransformHandler. See Rsbuild - api.transform
- Type:
import type { TransformHandler } from '@rsbuild/core';
type VirtualModules = Record<string, TransformHandler>;- Default:
{} - Example:
pluginVirtualModule({
virtualModules: {
'virtual-json-list': async ({ addDependency, addContextDependency }) => {
const jsonFolderPath = join(__dirname, 'json');
const ls = await readdir(jsonFolderPath);
addContextDependency(jsonFolderPath);
const res: Record<string, unknown> = {};
for (const file of ls) {
if (file.endsWith('.json')) {
const jsonFilePath = join(jsonFolderPath, file);
const jsonContent = await readFile(jsonFilePath, 'utf-8');
addDependency(jsonFilePath);
res[file] = JSON.parse(jsonContent);
}
}
return `export default ${JSON.stringify(res)}`;
},
},
});import jsonList from 'virtual-json-list';
console.log(jsonList);The name of the virtual module folder based on api.context.rootPath
- Type:
string - Default:
.rsbuild-virtual-module - Example:
pluginVirtualModule({
tempDir: 'src',
virtualModules: {
'virtual-foo': async () => {
return 'export default {}';
},
},
});The actual virtual module is ./src/virtual-foo.js
MIT.