UNPKG

1.6 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const ConstDependency = require("./dependencies/ConstDependency");
8
9/** @typedef {import("./Compiler")} Compiler */
10
11class UseStrictPlugin {
12 /**
13 * @param {Compiler} compiler Webpack Compiler
14 * @returns {void}
15 */
16 apply(compiler) {
17 compiler.hooks.compilation.tap(
18 "UseStrictPlugin",
19 (compilation, { normalModuleFactory }) => {
20 const handler = parser => {
21 parser.hooks.program.tap("UseStrictPlugin", ast => {
22 const firstNode = ast.body[0];
23 if (
24 firstNode &&
25 firstNode.type === "ExpressionStatement" &&
26 firstNode.expression.type === "Literal" &&
27 firstNode.expression.value === "use strict"
28 ) {
29 // Remove "use strict" expression. It will be added later by the renderer again.
30 // This is necessary in order to not break the strict mode when webpack prepends code.
31 // @see https://github.com/webpack/webpack/issues/1970
32 const dep = new ConstDependency("", firstNode.range);
33 dep.loc = firstNode.loc;
34 parser.state.current.addDependency(dep);
35 parser.state.module.buildInfo.strict = true;
36 }
37 });
38 };
39
40 normalModuleFactory.hooks.parser
41 .for("javascript/auto")
42 .tap("UseStrictPlugin", handler);
43 normalModuleFactory.hooks.parser
44 .for("javascript/dynamic")
45 .tap("UseStrictPlugin", handler);
46 normalModuleFactory.hooks.parser
47 .for("javascript/esm")
48 .tap("UseStrictPlugin", handler);
49 }
50 );
51 }
52}
53
54module.exports = UseStrictPlugin;