UseStrictPlugin.js 1.8 KB

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