EvalSourceMapDevToolPlugin.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. * Creates an instance of EvalSourceMapDevToolPlugin.
  39. * @param {SourceMapDevToolPluginOptions | string=} inputOptions Options object
  40. */
  41. constructor(inputOptions = {}) {
  42. /** @type {SourceMapDevToolPluginOptions} */
  43. let options;
  44. if (typeof inputOptions === "string") {
  45. options = {
  46. append: inputOptions
  47. };
  48. } else {
  49. options = inputOptions;
  50. }
  51. /** @type {string} */
  52. this.sourceMapComment =
  53. options.append && typeof options.append !== "function"
  54. ? options.append
  55. : "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
  56. /** @type {DevtoolModuleFilenameTemplate} */
  57. this.moduleFilenameTemplate =
  58. options.moduleFilenameTemplate ||
  59. "webpack://[namespace]/[resource-path]?[hash]";
  60. /** @type {DevtoolNamespace} */
  61. this.namespace = options.namespace || "";
  62. /** @type {SourceMapDevToolPluginOptions} */
  63. this.options = options;
  64. }
  65. /**
  66. * Applies the plugin by registering its hooks on the compiler.
  67. * @param {Compiler} compiler the compiler instance
  68. * @returns {void}
  69. */
  70. apply(compiler) {
  71. const options = this.options;
  72. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  73. const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
  74. new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
  75. const matchModule = ModuleFilenameHelpers.matchObject.bind(
  76. ModuleFilenameHelpers,
  77. options
  78. );
  79. hooks.renderModuleContent.tap(
  80. PLUGIN_NAME,
  81. (source, m, { chunk, runtimeTemplate, chunkGraph }) => {
  82. const cachedSource = cache.get(source);
  83. if (cachedSource !== undefined) {
  84. return cachedSource;
  85. }
  86. /**
  87. * Returns result.
  88. * @param {Source} r result
  89. * @returns {Source} result
  90. */
  91. const result = (r) => {
  92. cache.set(source, r);
  93. return r;
  94. };
  95. if (m instanceof NormalModule) {
  96. const module = /** @type {NormalModule} */ (m);
  97. if (!matchModule(module.resource)) {
  98. return result(source);
  99. }
  100. } else if (m instanceof ConcatenatedModule) {
  101. const concatModule = /** @type {ConcatenatedModule} */ (m);
  102. if (concatModule.rootModule instanceof NormalModule) {
  103. const module = /** @type {NormalModule} */ (
  104. concatModule.rootModule
  105. );
  106. if (!matchModule(module.resource)) {
  107. return result(source);
  108. }
  109. } else {
  110. return result(source);
  111. }
  112. } else {
  113. return result(source);
  114. }
  115. const namespace = compilation.getPath(this.namespace, {
  116. chunk
  117. });
  118. /** @type {RawSourceMap} */
  119. let sourceMap;
  120. /** @type {string | Buffer} */
  121. let content;
  122. if (source.sourceAndMap) {
  123. const sourceAndMap = source.sourceAndMap(options);
  124. sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map);
  125. content = sourceAndMap.source;
  126. } else {
  127. sourceMap = /** @type {RawSourceMap} */ (source.map(options));
  128. content = source.source();
  129. }
  130. if (!sourceMap) {
  131. return result(source);
  132. }
  133. // Clone (flat) the sourcemap to ensure that the mutations below do not persist.
  134. sourceMap = { ...sourceMap };
  135. const context = compiler.context;
  136. const root = compiler.root;
  137. const modules = sourceMap.sources.map((source) => {
  138. if (!source.startsWith("webpack://")) return source;
  139. source = makePathsAbsolute(context, source.slice(10), root);
  140. const module = compilation.findModule(source);
  141. return module || source;
  142. });
  143. let moduleFilenames = modules.map((module) =>
  144. ModuleFilenameHelpers.createFilename(
  145. module,
  146. {
  147. moduleFilenameTemplate: this.moduleFilenameTemplate,
  148. namespace
  149. },
  150. {
  151. requestShortener: runtimeTemplate.requestShortener,
  152. chunkGraph,
  153. hashFunction: compilation.outputOptions.hashFunction
  154. }
  155. )
  156. );
  157. moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
  158. moduleFilenames,
  159. (filename, i, n) => {
  160. for (let j = 0; j < n; j++) filename += "*";
  161. return filename;
  162. }
  163. );
  164. sourceMap.sources = moduleFilenames;
  165. if (options.ignoreList) {
  166. const ignoreList = sourceMap.sources.reduce(
  167. /** @type {(acc: number[], sourceName: string, idx: number) => number[]} */ (
  168. (acc, sourceName, idx) => {
  169. const rule = /** @type {Rules} */ (options.ignoreList);
  170. if (ModuleFilenameHelpers.matchPart(sourceName, rule)) {
  171. acc.push(idx);
  172. }
  173. return acc;
  174. }
  175. ),
  176. []
  177. );
  178. if (ignoreList.length > 0) {
  179. sourceMap.ignoreList = ignoreList;
  180. }
  181. }
  182. if (options.noSources) {
  183. sourceMap.sourcesContent = undefined;
  184. }
  185. sourceMap.sourceRoot = options.sourceRoot || "";
  186. const moduleId =
  187. /** @type {ModuleId} */
  188. (chunkGraph.getModuleId(m));
  189. sourceMap.file =
  190. typeof moduleId === "number" ? `${moduleId}.js` : moduleId;
  191. if (options.debugIds) {
  192. sourceMap.debugId = generateDebugId(content, sourceMap.file);
  193. }
  194. const footer = `${this.sourceMapComment.replace(
  195. /\[url\]/g,
  196. `data:application/json;charset=utf-8;base64,${Buffer.from(
  197. JSON.stringify(sourceMap),
  198. "utf8"
  199. ).toString("base64")}`
  200. )}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
  201. return result(
  202. new RawSource(
  203. `eval(${
  204. compilation.outputOptions.trustedTypes
  205. ? `${RuntimeGlobals.createScript}(${JSON.stringify(
  206. `{${content + footer}\n}`
  207. )})`
  208. : JSON.stringify(`{${content + footer}\n}`)
  209. });`
  210. )
  211. );
  212. }
  213. );
  214. hooks.inlineInRuntimeBailout.tap(
  215. PLUGIN_NAME,
  216. () => "the eval-source-map devtool is used."
  217. );
  218. hooks.render.tap(
  219. PLUGIN_NAME,
  220. (source) => new ConcatSource(devtoolWarning, source)
  221. );
  222. hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => {
  223. hash.update(PLUGIN_NAME);
  224. hash.update("2");
  225. });
  226. if (compilation.outputOptions.trustedTypes) {
  227. compilation.hooks.additionalModuleRuntimeRequirements.tap(
  228. PLUGIN_NAME,
  229. (module, set, context) => {
  230. set.add(RuntimeGlobals.createScript);
  231. }
  232. );
  233. }
  234. });
  235. }
  236. }
  237. module.exports = EvalSourceMapDevToolPlugin;