提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
10 KiB

  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Jason Anderson @diurnalist
  4. */
  5. "use strict";
  6. const { basename, extname } = require("path");
  7. const util = require("util");
  8. const mime = require("mime-types");
  9. const Chunk = require("./Chunk");
  10. const Module = require("./Module");
  11. const { parseResource } = require("./util/identifier");
  12. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  13. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  14. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  15. /** @typedef {import("./Compilation").PathData} PathData */
  16. /** @typedef {import("./Compiler")} Compiler */
  17. const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
  18. /**
  19. * @param {string | number} id id
  20. * @returns {string | number} result
  21. */
  22. const prepareId = (id) => {
  23. if (typeof id !== "string") return id;
  24. if (/^"\s\+*.*\+\s*"$/.test(id)) {
  25. const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
  26. return `" + (${
  27. /** @type {string[]} */ (match)[1]
  28. } + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
  29. }
  30. return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_");
  31. };
  32. /**
  33. * @callback ReplacerFunction
  34. * @param {string} match
  35. * @param {string | undefined} arg
  36. * @param {string} input
  37. */
  38. /**
  39. * @param {ReplacerFunction} replacer replacer
  40. * @param {((arg0: number) => string) | undefined} handler handler
  41. * @param {AssetInfo | undefined} assetInfo asset info
  42. * @param {string} hashName hash name
  43. * @returns {Replacer} hash replacer function
  44. */
  45. const hashLength = (replacer, handler, assetInfo, hashName) => {
  46. /** @type {Replacer} */
  47. const fn = (match, arg, input) => {
  48. let result;
  49. const length = arg && Number.parseInt(arg, 10);
  50. if (length && handler) {
  51. result = handler(length);
  52. } else {
  53. const hash = replacer(match, arg, input);
  54. result = length ? hash.slice(0, length) : hash;
  55. }
  56. if (assetInfo) {
  57. assetInfo.immutable = true;
  58. if (Array.isArray(assetInfo[hashName])) {
  59. assetInfo[hashName] = [...assetInfo[hashName], result];
  60. } else if (assetInfo[hashName]) {
  61. assetInfo[hashName] = [assetInfo[hashName], result];
  62. } else {
  63. assetInfo[hashName] = result;
  64. }
  65. }
  66. return result;
  67. };
  68. return fn;
  69. };
  70. /** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
  71. /**
  72. * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
  73. * @param {boolean=} allowEmpty allow empty
  74. * @returns {Replacer} replacer
  75. */
  76. const replacer = (value, allowEmpty) => {
  77. /** @type {Replacer} */
  78. const fn = (match, arg, input) => {
  79. if (typeof value === "function") {
  80. value = value();
  81. }
  82. if (value === null || value === undefined) {
  83. if (!allowEmpty) {
  84. throw new Error(
  85. `Path variable ${match} not implemented in this context: ${input}`
  86. );
  87. }
  88. return "";
  89. }
  90. return `${value}`;
  91. };
  92. return fn;
  93. };
  94. const deprecationCache = new Map();
  95. const deprecatedFunction = (() => () => {})();
  96. /**
  97. * @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
  98. * @param {T} fn function
  99. * @param {string} message message
  100. * @param {string} code code
  101. * @returns {T} function with deprecation output
  102. */
  103. const deprecated = (fn, message, code) => {
  104. let d = deprecationCache.get(message);
  105. if (d === undefined) {
  106. d = util.deprecate(deprecatedFunction, message, code);
  107. deprecationCache.set(message, d);
  108. }
  109. return /** @type {T} */ (
  110. (...args) => {
  111. d();
  112. return fn(...args);
  113. }
  114. );
  115. };
  116. /** @typedef {(pathData: PathData, assetInfo?: AssetInfo) => string} TemplatePathFn */
  117. /** @typedef {string | TemplatePathFn} TemplatePath */
  118. /**
  119. * @param {TemplatePath} path the raw path
  120. * @param {PathData} data context data
  121. * @param {AssetInfo | undefined} assetInfo extra info about the asset (will be written to)
  122. * @returns {string} the interpolated path
  123. */
  124. const replacePathVariables = (path, data, assetInfo) => {
  125. const chunkGraph = data.chunkGraph;
  126. /** @type {Map<string, Replacer>} */
  127. const replacements = new Map();
  128. // Filename context
  129. //
  130. // Placeholders
  131. //
  132. // for /some/path/file.js?query#fragment:
  133. // [file] - /some/path/file.js
  134. // [query] - ?query
  135. // [fragment] - #fragment
  136. // [base] - file.js
  137. // [path] - /some/path/
  138. // [name] - file
  139. // [ext] - .js
  140. if (typeof data.filename === "string") {
  141. // check that filename is data uri
  142. const match = data.filename.match(/^data:([^;,]+)/);
  143. if (match) {
  144. const ext = mime.extension(match[1]);
  145. const emptyReplacer = replacer("", true);
  146. // "XXXX" used for `updateHash`, so we don't need it here
  147. const contentHash =
  148. data.contentHash && !/X+/.test(data.contentHash)
  149. ? data.contentHash
  150. : false;
  151. const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
  152. replacements.set("file", emptyReplacer);
  153. replacements.set("query", emptyReplacer);
  154. replacements.set("fragment", emptyReplacer);
  155. replacements.set("path", emptyReplacer);
  156. replacements.set("base", baseReplacer);
  157. replacements.set("name", baseReplacer);
  158. replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
  159. // Legacy
  160. replacements.set(
  161. "filebase",
  162. deprecated(
  163. baseReplacer,
  164. "[filebase] is now [base]",
  165. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  166. )
  167. );
  168. } else {
  169. const { path: file, query, fragment } = parseResource(data.filename);
  170. const ext = extname(file);
  171. const base = basename(file);
  172. const name = base.slice(0, base.length - ext.length);
  173. const path = file.slice(0, file.length - base.length);
  174. replacements.set("file", replacer(file));
  175. replacements.set("query", replacer(query, true));
  176. replacements.set("fragment", replacer(fragment, true));
  177. replacements.set("path", replacer(path, true));
  178. replacements.set("base", replacer(base));
  179. replacements.set("name", replacer(name));
  180. replacements.set("ext", replacer(ext, true));
  181. // Legacy
  182. replacements.set(
  183. "filebase",
  184. deprecated(
  185. replacer(base),
  186. "[filebase] is now [base]",
  187. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  188. )
  189. );
  190. }
  191. }
  192. // Compilation context
  193. //
  194. // Placeholders
  195. //
  196. // [fullhash] - data.hash (3a4b5c6e7f)
  197. //
  198. // Legacy Placeholders
  199. //
  200. // [hash] - data.hash (3a4b5c6e7f)
  201. if (data.hash) {
  202. const hashReplacer = hashLength(
  203. replacer(data.hash),
  204. data.hashWithLength,
  205. assetInfo,
  206. "fullhash"
  207. );
  208. replacements.set("fullhash", hashReplacer);
  209. // Legacy
  210. replacements.set(
  211. "hash",
  212. deprecated(
  213. hashReplacer,
  214. "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)",
  215. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH"
  216. )
  217. );
  218. }
  219. // Chunk Context
  220. //
  221. // Placeholders
  222. //
  223. // [id] - chunk.id (0.js)
  224. // [name] - chunk.name (app.js)
  225. // [chunkhash] - chunk.hash (7823t4t4.js)
  226. // [contenthash] - chunk.contentHash[type] (3256u3zg.js)
  227. if (data.chunk) {
  228. const chunk = data.chunk;
  229. const contentHashType = data.contentHashType;
  230. const idReplacer = replacer(chunk.id);
  231. const nameReplacer = replacer(chunk.name || chunk.id);
  232. const chunkhashReplacer = hashLength(
  233. replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash),
  234. "hashWithLength" in chunk ? chunk.hashWithLength : undefined,
  235. assetInfo,
  236. "chunkhash"
  237. );
  238. const contenthashReplacer = hashLength(
  239. replacer(
  240. data.contentHash ||
  241. (contentHashType &&
  242. chunk.contentHash &&
  243. chunk.contentHash[contentHashType])
  244. ),
  245. data.contentHashWithLength ||
  246. ("contentHashWithLength" in chunk && chunk.contentHashWithLength
  247. ? chunk.contentHashWithLength[/** @type {string} */ (contentHashType)]
  248. : undefined),
  249. assetInfo,
  250. "contenthash"
  251. );
  252. replacements.set("id", idReplacer);
  253. replacements.set("name", nameReplacer);
  254. replacements.set("chunkhash", chunkhashReplacer);
  255. replacements.set("contenthash", contenthashReplacer);
  256. }
  257. // Module Context
  258. //
  259. // Placeholders
  260. //
  261. // [id] - module.id (2.png)
  262. // [hash] - module.hash (6237543873.png)
  263. //
  264. // Legacy Placeholders
  265. //
  266. // [moduleid] - module.id (2.png)
  267. // [modulehash] - module.hash (6237543873.png)
  268. if (data.module) {
  269. const module = data.module;
  270. const idReplacer = replacer(() =>
  271. prepareId(
  272. module instanceof Module
  273. ? /** @type {ModuleId} */
  274. (/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
  275. : module.id
  276. )
  277. );
  278. const moduleHashReplacer = hashLength(
  279. replacer(() =>
  280. module instanceof Module
  281. ? /** @type {ChunkGraph} */
  282. (chunkGraph).getRenderedModuleHash(module, data.runtime)
  283. : module.hash
  284. ),
  285. "hashWithLength" in module ? module.hashWithLength : undefined,
  286. assetInfo,
  287. "modulehash"
  288. );
  289. const contentHashReplacer = hashLength(
  290. replacer(/** @type {string} */ (data.contentHash)),
  291. undefined,
  292. assetInfo,
  293. "contenthash"
  294. );
  295. replacements.set("id", idReplacer);
  296. replacements.set("modulehash", moduleHashReplacer);
  297. replacements.set("contenthash", contentHashReplacer);
  298. replacements.set(
  299. "hash",
  300. data.contentHash ? contentHashReplacer : moduleHashReplacer
  301. );
  302. // Legacy
  303. replacements.set(
  304. "moduleid",
  305. deprecated(
  306. idReplacer,
  307. "[moduleid] is now [id]",
  308. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID"
  309. )
  310. );
  311. }
  312. // Other things
  313. if (data.url) {
  314. replacements.set("url", replacer(data.url));
  315. }
  316. if (typeof data.runtime === "string") {
  317. replacements.set(
  318. "runtime",
  319. replacer(() => prepareId(/** @type {string} */ (data.runtime)))
  320. );
  321. } else {
  322. replacements.set("runtime", replacer("_"));
  323. }
  324. if (typeof path === "function") {
  325. path = path(data, assetInfo);
  326. }
  327. path = path.replace(REGEXP, (match, content) => {
  328. if (content.length + 2 === match.length) {
  329. const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
  330. if (!contentMatch) return match;
  331. const [, kind, arg] = contentMatch;
  332. const replacer = replacements.get(kind);
  333. if (replacer !== undefined) {
  334. return replacer(match, arg, /** @type {string} */ (path));
  335. }
  336. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  337. return `[${match.slice(2, -2)}]`;
  338. }
  339. return match;
  340. });
  341. return path;
  342. };
  343. const plugin = "TemplatedPathPlugin";
  344. class TemplatedPathPlugin {
  345. /**
  346. * Apply the plugin
  347. * @param {Compiler} compiler the compiler instance
  348. * @returns {void}
  349. */
  350. apply(compiler) {
  351. compiler.hooks.compilation.tap(plugin, (compilation) => {
  352. compilation.hooks.assetPath.tap(plugin, replacePathVariables);
  353. });
  354. }
  355. }
  356. module.exports = TemplatedPathPlugin;