UseStrictPlugin.js 1.6 KB

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