UseStrictPlugin.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435
  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. class UseStrictPlugin {
  8. apply(compiler) {
  9. compiler.plugin("compilation", (compilation, params) => {
  10. params.normalModuleFactory.plugin("parser", (parser) => {
  11. const parserInstance = parser;
  12. parser.plugin("program", (ast) => {
  13. const firstNode = ast.body[0];
  14. if(firstNode &&
  15. firstNode.type === "ExpressionStatement" &&
  16. firstNode.expression.type === "Literal" &&
  17. firstNode.expression.value === "use strict") {
  18. // Remove "use strict" expression. It will be added later by the renderer again.
  19. // This is necessary in order to not break the strict mode when webpack prepends code.
  20. // @see https://github.com/webpack/webpack/issues/1970
  21. const dep = new ConstDependency("", firstNode.range);
  22. dep.loc = firstNode.loc;
  23. parserInstance.state.current.addDependency(dep);
  24. parserInstance.state.module.strict = true;
  25. }
  26. });
  27. });
  28. });
  29. }
  30. }
  31. module.exports = UseStrictPlugin;