UseStrictPlugin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. * Apply the plugin
  11. * @param {Compiler} compiler the compiler instance
  12. * @returns {void}
  13. */
  14. apply(compiler) {
  15. compiler.hooks.compilation.tap(
  16. "UseStrictPlugin",
  17. (compilation, { normalModuleFactory }) => {
  18. const handler = parser => {
  19. parser.hooks.program.tap("UseStrictPlugin", ast => {
  20. const firstNode = ast.body[0];
  21. if (
  22. firstNode &&
  23. firstNode.type === "ExpressionStatement" &&
  24. firstNode.expression.type === "Literal" &&
  25. firstNode.expression.value === "use strict"
  26. ) {
  27. // Remove "use strict" expression. It will be added later by the renderer again.
  28. // This is necessary in order to not break the strict mode when webpack prepends code.
  29. // @see https://github.com/webpack/webpack/issues/1970
  30. const dep = new ConstDependency("", firstNode.range);
  31. dep.loc = firstNode.loc;
  32. parser.state.module.addPresentationalDependency(dep);
  33. parser.state.module.buildInfo.strict = true;
  34. }
  35. });
  36. };
  37. normalModuleFactory.hooks.parser
  38. .for("javascript/auto")
  39. .tap("UseStrictPlugin", handler);
  40. normalModuleFactory.hooks.parser
  41. .for("javascript/dynamic")
  42. .tap("UseStrictPlugin", handler);
  43. normalModuleFactory.hooks.parser
  44. .for("javascript/esm")
  45. .tap("UseStrictPlugin", handler);
  46. }
  47. );
  48. }
  49. }
  50. module.exports = UseStrictPlugin;