TemplatedPathPlugin.js 9.8 KB

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