TemplatedPathPlugin.js 9.4 KB

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