The simplest and most flexible way to build with a compiling magic 🪄
npm install rsbuild-plugin-virtual-moduleThe 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:
``bash`
npm add rsbuild-plugin-virtual-module -D
Add plugin to your rsbuild.config.ts:
`ts
// rsbuild.config.ts
import { pluginVirtualModule } from 'rsbuild-plugin-virtual-module';
export default {
plugins: [
pluginVirtualModule({
virtualModules: {
'virtual-foo': async () => {
return 'export default {}';
},
},
}),
],
};
`
`ts
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:
`ts
import type { TransformHandler } from '@rsbuild/core';
type VirtualModules = Record
`
- Default: {}
- Example:
`js
pluginVirtualModule({
virtualModules: {
'virtual-json-list': async ({ addDependency, addContextDependency }) => {
const jsonFolderPath = join(__dirname, 'json');
const ls = await readdir(jsonFolderPath);
addContextDependency(jsonFolderPath);
const res: Record
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)};`
},
},
});
`js`
import jsonList from 'virtual-json-list';
console.log(jsonList);
The name of the virtual module folder based on api.context.rootPath
- Type: string.rsbuild-virtual-module
- Default:
- Example:
`js`
pluginVirtualModule({
tempDir: 'src',
virtualModules: {
'virtual-foo': async () => {
return 'export default {}';
},
},
});
The actual virtual module is ./src/virtual-foo.js`
MIT.