UseStrictPlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  14. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  15. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  16. /** @typedef {import("./javascript/JavascriptParser").Range} Range */
  17. const PLUGIN_NAME = "UseStrictPlugin";
  18. class UseStrictPlugin {
  19. /**
  20. * Apply the plugin
  21. * @param {Compiler} compiler the compiler instance
  22. * @returns {void}
  23. */
  24. apply(compiler) {
  25. compiler.hooks.compilation.tap(
  26. PLUGIN_NAME,
  27. (compilation, { normalModuleFactory }) => {
  28. /**
  29. * @param {JavascriptParser} parser the parser
  30. */
  31. const handler = parser => {
  32. parser.hooks.program.tap(PLUGIN_NAME, ast => {
  33. const firstNode = ast.body[0];
  34. if (
  35. firstNode &&
  36. firstNode.type === "ExpressionStatement" &&
  37. firstNode.expression.type === "Literal" &&
  38. firstNode.expression.value === "use strict"
  39. ) {
  40. // Remove "use strict" expression. It will be added later by the renderer again.
  41. // This is necessary in order to not break the strict mode when webpack prepends code.
  42. // @see https://github.com/webpack/webpack/issues/1970
  43. const dep = new ConstDependency(
  44. "",
  45. /** @type {Range} */ (firstNode.range)
  46. );
  47. dep.loc = /** @type {DependencyLocation} */ (firstNode.loc);
  48. parser.state.module.addPresentationalDependency(dep);
  49. /** @type {BuildInfo} */
  50. (parser.state.module.buildInfo).strict = true;
  51. }
  52. });
  53. };
  54. normalModuleFactory.hooks.parser
  55. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  56. .tap(PLUGIN_NAME, handler);
  57. normalModuleFactory.hooks.parser
  58. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  59. .tap(PLUGIN_NAME, handler);
  60. normalModuleFactory.hooks.parser
  61. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  62. .tap(PLUGIN_NAME, handler);
  63. }
  64. );
  65. }
  66. }
  67. module.exports = UseStrictPlugin;