提交学习笔记专用
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.

225 lines
7.1 KiB

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