Skip to content

Commit 31582b2

Browse files
committed
docs: add support for context option in VirtualUrlPlugin for resolving relative imports in virtual modules
1 parent 29103a3 commit 31582b2

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

src/content/blog/2026-03-13-webpack-5-106.mdx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,40 @@ const { a } = require("./module");
8989
// Also supported
9090
const { a, b } = module.require("./module");
9191
```
92+
93+
## Context Support for VirtualUrlPlugin
94+
95+
`VirtualUrlPlugin` (via `webpack.experiments.schemes.VirtualUrlPlugin`) now supports a `context` option that defines the **base directory used to resolve relative imports inside virtual modules**. This feature is currently **experimental**, as it is part of the `experiments.schemes` API.
96+
97+
This makes virtual modules behave more like real files: code such as `import "./utils"` resolves consistently instead of falling back to `compiler.context` and potentially resolving incorrectly.
98+
99+
`context` can be set per virtual module (inside the module definition) or as a plugin level default. It defaults to `"auto"`, which tries to infer the context from the virtual module id or path; otherwise it falls back to `compiler.context`. Conceptually, when you set `context` for a module, webpack treats that virtual module *as if it lived inside that directory* for resolving relative paths.
100+
101+
For example, if you define a virtual module id `virtual/table.js` with `context: path.join(__dirname, "src/components")`, then its internal `import "./utils"` is resolved as if the file were `src/components/table.js` importing `src/components/utils.js`.
102+
103+
```js
104+
const path = require("path");
105+
const webpack = require("webpack");
106+
107+
module.exports = {
108+
plugins: [
109+
new webpack.experiments.schemes.VirtualUrlPlugin(
110+
{
111+
"src/components/button.js": {
112+
context: "auto",
113+
source() {
114+
return "import { trim } from './utils'; export const button = trim('button ');";
115+
}
116+
},
117+
"virtual/table.js": {
118+
context: path.join(__dirname, "src/components"),
119+
source() {
120+
return "import { trim } from './utils'; export const table = trim('table ');";
121+
}
122+
}
123+
},
124+
{ context: "auto" }
125+
)
126+
]
127+
};
128+
```

0 commit comments

Comments
 (0)