Allow creating virtual modules of any type, such as .ts, .json, .css, etc. default is .js.
import webpack from "webpack";
new webpack.experiments.schemes.VirtualUrlPlugin({
myModule: 'export const msg = "from virtual module"',
});src/app.js
import { msg } from "virtual:myModule";
console.log(msg);Create a virtual module that generates build information
import webpack from "webpack";
new webpack.experiments.schemes.VirtualUrlPlugin({
buildInfo: {
source() {
return `export const buildTime = ${Date.now()}`;
},
version: true,
},
});src/app.js
import { buildTime } from "virtual:buildInfo";
console.log(`App version: ${buildTime}`);Use custom schema
import webpack from "webpack";
new webpack.experiments.schemes.VirtualUrlPlugin(
{
myModule: 'export const msg = "from virtual module"',
},
"v",
);src/app.js
import { msg } from "v:myModule";
console.log(msg);Create multiple virtual modules of different types
import webpack from "webpack";
new webpack.experiments.schemes.VirtualUrlPlugin({
myCssModule: {
type: ".css",
source: "body{background-color: powderblue;}",
},
myJsonModule: {
type: ".json",
source: '{"name": "virtual-url-plugin"}',
},
});src/app.js
import json from "virtual:myJsonModule";
import "virtual:myCssModule";Virtualize the routing file
import path from "node:path";
import { fileURLToPath } from "node:url";
import webpack from "webpack";
// For compatibility with older Node.js versions
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const watchDir = path.join(__dirname, "./src/routes");
new webpack.experiments.schemes.VirtualUrlPlugin({
routes: {
source(loaderContext) {
// Use addContextDependency to monitor the addition or removal of subdirectories in watchDir to trigger the rebuilding of virtual modules.
loaderContext.addContextDependency(watchDir);
const files = fs.readdirSync(watchDir);
return `
export const routes = {
${files.map((key) => `${key.split(".")[0]}: () => import('./src/routes/${key}')`).join(",\n")}
}
`;
},
},
});src/app.js
import { routes } from "virtual:routes";module.type (string): Content type of the virtual module.module.source (string | ((loaderContext: import('webpack').LoaderContext<T>) => Promise<string> | string)): Factory function for generating the content of virtual module.
module.version(boolean | string | () => string): When a invalidate is triggered, the source function is called again if the value of the version is different from the previous one. If set to true it will always trigger.
schema (string): Customizable virtual module schema, default is virtual.