UseStrictPlugin.js 2.5 KB

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