1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | */
|
---|
4 |
|
---|
5 | "use strict";
|
---|
6 |
|
---|
7 | const RuntimeGlobals = require("../RuntimeGlobals");
|
---|
8 | const RuntimeModule = require("../RuntimeModule");
|
---|
9 | const Template = require("../Template");
|
---|
10 | const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin");
|
---|
11 | const { getUndoPath } = require("../util/identifier");
|
---|
12 |
|
---|
13 | class AutoPublicPathRuntimeModule extends RuntimeModule {
|
---|
14 | constructor() {
|
---|
15 | super("publicPath", RuntimeModule.STAGE_BASIC);
|
---|
16 | }
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * @returns {string} runtime code
|
---|
20 | */
|
---|
21 | generate() {
|
---|
22 | const { compilation } = this;
|
---|
23 | const { scriptType, importMetaName, path } = compilation.outputOptions;
|
---|
24 | const chunkName = compilation.getPath(
|
---|
25 | JavascriptModulesPlugin.getChunkFilenameTemplate(
|
---|
26 | this.chunk,
|
---|
27 | compilation.outputOptions
|
---|
28 | ),
|
---|
29 | {
|
---|
30 | chunk: this.chunk,
|
---|
31 | contentHashType: "javascript"
|
---|
32 | }
|
---|
33 | );
|
---|
34 | const undoPath = getUndoPath(chunkName, path, false);
|
---|
35 |
|
---|
36 | return Template.asString([
|
---|
37 | "var scriptUrl;",
|
---|
38 | scriptType === "module"
|
---|
39 | ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url`
|
---|
40 | : Template.asString([
|
---|
41 | `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`,
|
---|
42 | `var document = ${RuntimeGlobals.global}.document;`,
|
---|
43 | "if (!scriptUrl && document) {",
|
---|
44 | Template.indent([
|
---|
45 | `if (document.currentScript)`,
|
---|
46 | Template.indent(`scriptUrl = document.currentScript.src`),
|
---|
47 | "if (!scriptUrl) {",
|
---|
48 | Template.indent([
|
---|
49 | 'var scripts = document.getElementsByTagName("script");',
|
---|
50 | "if(scripts.length) scriptUrl = scripts[scripts.length - 1].src"
|
---|
51 | ]),
|
---|
52 | "}"
|
---|
53 | ]),
|
---|
54 | "}"
|
---|
55 | ]),
|
---|
56 | "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration",
|
---|
57 | '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.',
|
---|
58 | 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");',
|
---|
59 | 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");',
|
---|
60 | !undoPath
|
---|
61 | ? `${RuntimeGlobals.publicPath} = scriptUrl;`
|
---|
62 | : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify(
|
---|
63 | undoPath
|
---|
64 | )};`
|
---|
65 | ]);
|
---|
66 | }
|
---|
67 | }
|
---|
68 |
|
---|
69 | module.exports = AutoPublicPathRuntimeModule;
|
---|