EvalSourceMapDevToolPlugin.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource, RawSource } = require("webpack-sources");
  7. const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
  8. const NormalModule = require("./NormalModule");
  9. const RuntimeGlobals = require("./RuntimeGlobals");
  10. const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
  11. const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
  12. const ConcatenatedModule = require("./optimize/ConcatenatedModule");
  13. const generateDebugId = require("./util/generateDebugId");
  14. const { makePathsAbsolute } = require("./util/identifier");
  15. /** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */
  16. /** @typedef {import("webpack-sources").Source} Source */
  17. /** @typedef {import("../declarations/WebpackOptions").DevtoolNamespace} DevtoolNamespace */
  18. /** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
  19. /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
  20. /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").Rules} Rules */
  21. /** @typedef {import("./Compiler")} Compiler */
  22. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  23. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  24. /** @type {WeakMap<Source, Source>} */
  25. const cache = new WeakMap();
  26. const devtoolWarning = new RawSource(`/*
  27. * ATTENTION: An "eval-source-map" devtool has been used.
  28. * This devtool is neither made for production nor for readable output files.
  29. * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
  30. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
  31. * or disable the default devtool with "devtool: false".
  32. * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
  33. */
  34. `);
  35. const PLUGIN_NAME = "EvalSourceMapDevToolPlugin";
  36. class EvalSourceMapDevToolPlugin {
  37. /**
  38. * @param {SourceMapDevToolPluginOptions | string=} inputOptions Options object
  39. */
  40. constructor(inputOptions = {}) {
  41. /** @type {SourceMapDevToolPluginOptions} */
  42. let options;
  43. if (typeof inputOptions === "string") {
  44. options = {
  45. append: inputOptions
  46. };
  47. } else {
  48. options = inputOptions;
  49. }
  50. /** @type {string} */
  51. this.sourceMapComment =
  52. options.append && typeof options.append !== "function"
  53. ? options.append
  54. : "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
  55. /** @type {DevtoolModuleFilenameTemplate} */
  56. this.moduleFilenameTemplate =
  57. options.moduleFilenameTemplate ||
  58. "webpack://[namespace]/[resource-path]?[hash]";
  59. /** @type {DevtoolNamespace} */
  60. this.namespace = options.namespace || "";
  61. /** @type {SourceMapDevToolPluginOptions} */
  62. this.options = options;
  63. }
  64. /**
  65. * Apply the plugin
  66. * @param {Compiler} compiler the compiler instance
  67. * @returns {void}
  68. */
  69. apply(compiler) {
  70. const options = this.options;
  71. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  72. const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
  73. new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
  74. const matchModule = ModuleFilenameHelpers.matchObject.bind(
  75. ModuleFilenameHelpers,
  76. options
  77. );
  78. hooks.renderModuleContent.tap(
  79. PLUGIN_NAME,
  80. (source, m, { chunk, runtimeTemplate, chunkGraph }) => {
  81. const cachedSource = cache.get(source);
  82. if (cachedSource !== undefined) {
  83. return cachedSource;
  84. }
  85. /**
  86. * @param {Source} r result
  87. * @returns {Source} result
  88. */
  89. const result = (r) => {
  90. cache.set(source, r);
  91. return r;
  92. };
  93. if (m instanceof NormalModule) {
  94. const module = /** @type {NormalModule} */ (m);
  95. if (!matchModule(module.resource)) {
  96. return result(source);
  97. }
  98. } else if (m instanceof ConcatenatedModule) {
  99. const concatModule = /** @type {ConcatenatedModule} */ (m);
  100. if (concatModule.rootModule instanceof NormalModule) {
  101. const module = /** @type {NormalModule} */ (
  102. concatModule.rootModule
  103. );
  104. if (!matchModule(module.resource)) {
  105. return result(source);
  106. }
  107. } else {
  108. return result(source);
  109. }
  110. } else {
  111. return result(source);
  112. }
  113. const namespace = compilation.getPath(this.namespace, {
  114. chunk
  115. });
  116. /** @type {RawSourceMap} */
  117. let sourceMap;
  118. /** @type {string | Buffer} */
  119. let content;
  120. if (source.sourceAndMap) {
  121. const sourceAndMap = source.sourceAndMap(options);
  122. sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map);
  123. content = sourceAndMap.source;
  124. } else {
  125. sourceMap = /** @type {RawSourceMap} */ (source.map(options));
  126. content = source.source();
  127. }
  128. if (!sourceMap) {
  129. return result(source);
  130. }
  131. // Clone (flat) the sourcemap to ensure that the mutations below do not persist.
  132. sourceMap = { ...sourceMap };
  133. const context = compiler.context;
  134. const root = compiler.root;
  135. const modules = sourceMap.sources.map((source) => {
  136. if (!source.startsWith("webpack://")) return source;
  137. source = makePathsAbsolute(context, source.slice(10), root);
  138. const module = compilation.findModule(source);
  139. return module || source;
  140. });
  141. let moduleFilenames = modules.map((module) =>
  142. ModuleFilenameHelpers.createFilename(
  143. module,
  144. {
  145. moduleFilenameTemplate: this.moduleFilenameTemplate,
  146. namespace
  147. },
  148. {
  149. requestShortener: runtimeTemplate.requestShortener,
  150. chunkGraph,
  151. hashFunction: compilation.outputOptions.hashFunction
  152. }
  153. )
  154. );
  155. moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
  156. moduleFilenames,
  157. (filename, i, n) => {
  158. for (let j = 0; j < n; j++) filename += "*";
  159. return filename;
  160. }
  161. );
  162. sourceMap.sources = moduleFilenames;
  163. if (options.ignoreList) {
  164. const ignoreList = sourceMap.sources.reduce(
  165. /** @type {(acc: number[], sourceName: string, idx: number) => number[]} */ (
  166. (acc, sourceName, idx) => {
  167. const rule = /** @type {Rules} */ (options.ignoreList);
  168. if (ModuleFilenameHelpers.matchPart(sourceName, rule)) {
  169. acc.push(idx);
  170. }
  171. return acc;
  172. }
  173. ),
  174. []
  175. );
  176. if (ignoreList.length > 0) {
  177. sourceMap.ignoreList = ignoreList;
  178. }
  179. }
  180. if (options.noSources) {
  181. sourceMap.sourcesContent = undefined;
  182. }
  183. sourceMap.sourceRoot = options.sourceRoot || "";
  184. const moduleId =
  185. /** @type {ModuleId} */
  186. (chunkGraph.getModuleId(m));
  187. sourceMap.file =
  188. typeof moduleId === "number" ? `${moduleId}.js` : moduleId;
  189. if (options.debugIds) {
  190. sourceMap.debugId = generateDebugId(content, sourceMap.file);
  191. }
  192. const footer = `${this.sourceMapComment.replace(
  193. /\[url\]/g,
  194. `data:application/json;charset=utf-8;base64,${Buffer.from(
  195. JSON.stringify(sourceMap),
  196. "utf8"
  197. ).toString("base64")}`
  198. )}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
  199. return result(
  200. new RawSource(
  201. `eval(${
  202. compilation.outputOptions.trustedTypes
  203. ? `${RuntimeGlobals.createScript}(${JSON.stringify(
  204. `{${content + footer}\n}`
  205. )})`
  206. : JSON.stringify(`{${content + footer}\n}`)
  207. });`
  208. )
  209. );
  210. }
  211. );
  212. hooks.inlineInRuntimeBailout.tap(
  213. PLUGIN_NAME,
  214. () => "the eval-source-map devtool is used."
  215. );
  216. hooks.render.tap(
  217. PLUGIN_NAME,
  218. (source) => new ConcatSource(devtoolWarning, source)
  219. );
  220. hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
  221. hash.update(PLUGIN_NAME);
  222. hash.update("2");
  223. });
  224. if (compilation.outputOptions.trustedTypes) {
  225. compilation.hooks.additionalModuleRuntimeRequirements.tap(
  226. PLUGIN_NAME,
  227. (module, set, context) => {
  228. set.add(RuntimeGlobals.createScript);
  229. }
  230. );
  231. }
  232. });
  233. }
  234. }
  235. module.exports = EvalSourceMapDevToolPlugin;