UNPKG

2.97 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { ConcatSource, RawSource } = require("webpack-sources");
9const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
10const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
11
12/** @typedef {import("webpack-sources").Source} Source */
13/** @typedef {import("./Compiler")} Compiler */
14
15/** @type {WeakMap<Source, Source>} */
16const cache = new WeakMap();
17
18const devtoolWarning = new RawSource(`/*
19 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
20 * This devtool is not neither made for production nor for readable output files.
21 * It uses "eval()" calls to create a separate source file in the browser devtools.
22 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
23 * or disable the default devtool with "devtool: false".
24 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
25 */
26`);
27
28class EvalDevToolModulePlugin {
29 constructor(options) {
30 this.namespace = options.namespace || "";
31 this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]";
32 this.moduleFilenameTemplate =
33 options.moduleFilenameTemplate ||
34 "webpack://[namespace]/[resourcePath]?[loaders]";
35 }
36
37 /**
38 * Apply the plugin
39 * @param {Compiler} compiler the compiler instance
40 * @returns {void}
41 */
42 apply(compiler) {
43 compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => {
44 const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
45 hooks.renderModuleContent.tap(
46 "EvalDevToolModulePlugin",
47 (source, module, { runtimeTemplate, chunkGraph }) => {
48 const cacheEntry = cache.get(source);
49 if (cacheEntry !== undefined) return cacheEntry;
50 const content = source.source();
51 const str = ModuleFilenameHelpers.createFilename(
52 module,
53 {
54 moduleFilenameTemplate: this.moduleFilenameTemplate,
55 namespace: this.namespace
56 },
57 {
58 requestShortener: runtimeTemplate.requestShortener,
59 chunkGraph
60 }
61 );
62 const footer =
63 "\n" +
64 this.sourceUrlComment.replace(
65 /\[url\]/g,
66 encodeURI(str)
67 .replace(/%2F/g, "/")
68 .replace(/%20/g, "_")
69 .replace(/%5E/g, "^")
70 .replace(/%5C/g, "\\")
71 .replace(/^\//, "")
72 );
73 const result = new RawSource(
74 `eval(${JSON.stringify(content + footer)});`
75 );
76 cache.set(source, result);
77 return result;
78 }
79 );
80 hooks.render.tap(
81 "EvalDevToolModulePlugin",
82 source => new ConcatSource(devtoolWarning, source)
83 );
84 hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => {
85 hash.update("EvalDevToolModulePlugin");
86 hash.update("2");
87 });
88 });
89 }
90}
91
92module.exports = EvalDevToolModulePlugin;