8000 Adds a runtime variable __webpack_require__.dp to generate a dynamic path by arkapratimc · Pull Request #19238 · webpack/webpack · GitHub
[go: up one dir, main page]

Skip to content

Adds a runtime variable __webpack_require__.dp to generate a dynamic path #19238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/RuntimeTemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,15 @@ class RuntimeTemplate {
}
}

/**
* @param {string | { expr: string }} filename the file name of the resource
* @returns {string} the resultant public path expression
*/
generatePublicPath(filename) {
const publicPath = `typeof ${RuntimeGlobals.publicPath} === "function" ? ${RuntimeGlobals.publicPath}(${typeof filename === "object" ? filename.expr : `"${filename}"`}) : (${this.concatenation({ expr: RuntimeGlobals.publicPath }, filename)})`;
return publicPath;
}

/**
* @param {object} options options object
* @param {ChunkGraph} options.chunkGraph the chunk graph
Expand Down
5 changes: 1 addition & 4 deletions lib/asset/AssetGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,10 +366,7 @@ class AssetGenerator extends Generator {
} else if (type === "javascript") {
// add __webpack_require__.p
runtimeRequirements.add(RuntimeGlobals.publicPath);
assetPath = runtimeTemplate.concatenation(
{ expr: RuntimeGlobals.publicPath },
filename
);
assetPath = runtimeTemplate.generatePublicPath(filename);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should do it every where we have RuntimeGlobals.publicPath

} else if (type === "css-url") {
const compilation = runtimeTemplate.compilation;
const path =
Expand Down
8 changes: 4 additions & 4 deletions lib/css/CssLoadingRuntimeModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
"promises.push(installedChunkData[2] = promise);",
"",
"// start chunk loading",
`var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
`var url = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkCssFilename}(chunkId)` })};`,
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`var loadingEnded = ${runtimeTemplate.basicFunction(
Expand Down Expand Up @@ -366,7 +366,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
"}",
'link.rel = "prefetch";',
'link.as = "style";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkCssFilename}(chunkId)` })};`
]),
chunk
),
Expand Down Expand Up @@ -401,7 +401,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
"}",
'link.rel = "preload";',
'link.as = "style";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkCssFilename}(chunkId)` })};`,
crossOriginLoading
? crossOriginLoading === "use-credentials"
? 'link.crossOrigin = "use-credentials";'
Expand Down Expand Up @@ -462,7 +462,7 @@ class CssLoadingRuntimeModule extends RuntimeModule {
"applyHandlers.push(applyHandler);",
`chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
`var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
`var url = ${RuntimeGlobals.publicPath} + filename;`,
`var url = ${runtimeTemplate.generatePublicPath("filename")};`,
"var oldTag = loadStylesheet(chunkId, url);",
"if(!oldTag) return;",
`promises.push(new Promise(${runtimeTemplate.basicFunction(
Expand Down
4 changes: 2 additions & 2 deletions lib/esm/ModuleChunkLoadingRuntimeModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
"}",
'link.rel = "prefetch";',
'link.as = "script";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })};`
]),
chunk
),
Expand Down Expand Up @@ -308,7 +308,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
),
"}",
'link.rel = "modulepreload";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })};`,
crossOriginLoading
? crossOriginLoading === "use-credentials"
? 'link.crossOrigin = "use-credentials";'
Expand Down
2 changes: 1 addition & 1 deletion lib/web/FetchCompileAsyncWasmPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class FetchCompileAsyncWasmPlugin {
* @returns {string} code to load the wasm file
*/
const generateLoadBinaryCode = path =>
`fetch(${RuntimeGlobals.publicPath} + ${path})`;
`fetch(${compilation.runtimeTemplate.generatePublicPath({ expr: `${path}` })})`;

compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.instantiateWasm)
Expand Down
2 changes: 1 addition & 1 deletion lib/web/FetchCompileWasmPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class FetchCompileWasmPlugin {
* @returns {string} code to load the wasm file
*/
const generateLoadBinaryCode = path =>
`fetch(${RuntimeGlobals.publicPath} + ${path})`;
`fetch(${compilation.runtimeTemplate.generatePublicPath({ expr: `${path}` })})`;

compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkHandlers)
Expand Down
14 changes: 7 additions & 7 deletions lib/web/JsonpChunkLoadingRuntimeModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
"promises.push(installedChunkData[2] = promise);",
"",
"// start chunk loading",
`var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
`var url = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })};`,
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`var loadingEnded = ${runtimeTemplate.basicFunction(
Expand Down Expand Up @@ -243,7 +243,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
"}",
'link.rel = "prefetch";',
'link.as = "script";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })};`
]),
chunk
),
Expand Down Expand Up @@ -280,7 +280,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
? 'link.rel = "modulepreload";'
: 'link.rel = "preload";',
scriptType === "module" ? "" : 'link.as = "script";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
`link.href = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })};`,
crossOriginLoading
? crossOriginLoading === "use-credentials"
? 'link.crossOrigin = "use-credentials";'
Expand Down Expand Up @@ -315,7 +315,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
[
"waitingUpdateResolves[chunkId] = resolve;",
"// start update chunk loading",
`var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`,
`var url = ${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` })};`,
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`var loadingEnded = ${runtimeTemplate.basicFunction("event", [
Expand Down Expand Up @@ -394,9 +394,9 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
RuntimeGlobals.hmrDownloadManifest
} = ${runtimeTemplate.basicFunction("", [
'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
`return fetch(${RuntimeGlobals.publicPath} + ${
RuntimeGlobals.getUpdateManifestFilename
}()).then(${runtimeTemplate.basicFunction("response", [
`return fetch(${runtimeTemplate.generatePublicPath({
expr: `${RuntimeGlobals.getUpdateManifestFilename}()`
})}).then(${runtimeTemplate.basicFunction("response", [
"if(response.status === 404) return; // no update available",
'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
"return response.json();"
Expand Down
14 changes: 7 additions & 7 deletions lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,8 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
Template.indent(
`importScripts(${
withCreateScriptUrl
? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))`
: `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)`
? `${RuntimeGlobals.createScriptUrl}(${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })})`
: `${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkScriptFilename}(chunkId)` })}`
});`
),
"}"
Expand Down Expand Up @@ -192,8 +192,8 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
"// start update chunk loading",
`importScripts(${
withCreateScriptUrl
? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))`
: `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)`
? `${RuntimeGlobals.createScriptUrl}(${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` })})`
: `${runtimeTemplate.generatePublicPath({ expr: `${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` })}`
});`,
'if(!success) throw new Error("Loading update chunk failed for unknown reason");'
]),
Expand Down Expand Up @@ -230,9 +230,9 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
RuntimeGlobals.hmrDownloadManifest
} = ${runtimeTemplate.basicFunction("", [
'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");',
`return fetch(${RuntimeGlobals.publicPath} + ${
RuntimeGlobals.getUpdateManifestFilename
}()).then(${runtimeTemplate.basicFunction("response", [
`return fetch(${runtimeTemplate.generatePublicPath({
expr: `${RuntimeGlobals.getUpdateManifestFilename}()`
})}).then(${runtimeTemplate.basicFunction("response", [
"if(response.status === 404) return; // no update available",
'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);',
"return response.json();"
Expand Down
8 changes: 4 additions & 4 deletions test/Stats.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,10 @@ describe("Stats", () => {
"assets": Array [
Object {
"name": "entryB.js",
"size": 3081,
"size": 3119,
},
],
"assetsSize": 3081,
"assetsSize": 3119,
"auxiliaryAssets": undefined,
"auxiliaryAssetsSize": 0,
"childAssets": undefined,
Expand Down Expand Up @@ -238,10 +238,10 @@ describe("Stats", () => {
"info": Object {
"javascriptModule": false,
"minimized": true,
"size": 3081,
"size": 3119,
},
"name": "entryB.js",
"size": 3081,
"size": 3119,
"type": "asset",
},
Object {
Expand Down
6 changes: 6 additions & 0 deletions test/configCases/asset-modules/dynamic-base-uri/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
it("should handle different querystrings for assets correctly", () => {
__webpack_public_path__ = (filename) => "hey/" + filename
__webpack_base_uri__ = "https://example.com";
const file = new URL("../_images/file.png", import.meta.url);
expect(file.href).toMatch(/^https:\/\/example.com\/hey\/[0-9a-f]+.png$/);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
target: "web"
};
1 change: 1 addition & 0 deletions test/configCases/asset-url/dynamic/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a {}
21 changes: 21 additions & 0 deletions test/configCases/asset-url/dynamic/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
it("should handle import.meta.url in URL()", () => {
__webpack_public_path__ = (filename) => "hey/" + filename
const url = new URL("./index.css?query=yes#fragment", import.meta.url);

expect(url.href).toBe("hey/index.css?query=yes#fragment");
expect(url.origin).toBe("");
expect(url.protocol).toBe("");
expect(url.username).toBe("");
expec 9920 t(url.password).toBe("");
expect(url.host).toBe("");
expect(url.hostname).toBe("");
expect(url.port).toBe("");
expect(url.pathname).toBe("hey/index.css");
expect(url.search).toBe("?query=yes");
expect(url.searchParams.get("query")).toBe("yes");
expect(url.hash).toBe("#fragment");
expect(url + "").toBe("hey/index.css?query=yes#fragment");
expect(url.toString()).toBe("hey/index.css?query=yes#fragment");
expect(JSON.stringify(url)).toBe('"hey/index.css?query=yes#fragment"');
expect(url instanceof URL).toBe(true);
});
15 changes: 15 additions & 0 deletions test/configCases/asset-url/dynamic/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "development",
devtool: false,
output: {
assetModuleFilename: "[name][ext][query][fragment]"
},
module: {
parser: {
javascript: {
url: "relative"
}
}
}
};
1 change: 1 addition & 0 deletions types.d.ts
658D
Original file line number Diff line number Diff line change
Expand Up @@ -13719,6 +13719,7 @@ declare abstract class RuntimeTemplate {
*/
runtimeRequirements: Set<string>;
}): string;
generatePublicPath(filename: string | { expr: string }): string;
moduleNamespacePromise(__0: {
/**
* the chunk graph
Expand Down
Loading
0