webpack/lib/UseStrictPlugin.js

64 lines
1.8 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
2017-01-11 17:51:58 +08:00
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const ConstDependency = require("./dependencies/ConstDependency");
2018-07-09 20:48:28 +08:00
/** @typedef {import("./Compiler")} Compiler */
2018-06-20 20:52:27 +08:00
const PLUGIN_NAME = "UseStrictPlugin";
class UseStrictPlugin {
2018-06-20 20:52:27 +08:00
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
2018-11-03 04:05:46 +08:00
* @param {Compiler} compiler the compiler instance
2018-06-20 20:52:27 +08:00
* @returns {void}
*/
apply(compiler) {
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap(
PLUGIN_NAME,
2018-02-25 09:00:20 +08:00
(compilation, { normalModuleFactory }) => {
const handler = parser => {
parser.hooks.program.tap(PLUGIN_NAME, ast => {
2018-02-25 09:00:20 +08:00
const firstNode = ast.body[0];
if (
firstNode &&
firstNode.type === "ExpressionStatement" &&
firstNode.expression.type === "Literal" &&
firstNode.expression.value === "use strict"
) {
// Remove "use strict" expression. It will be added later by the renderer again.
// This is necessary in order to not break the strict mode when webpack prepends code.
// @see https://github.com/webpack/webpack/issues/1970
const dep = new ConstDependency("", firstNode.range);
dep.loc = firstNode.loc;
parser.state.module.addPresentationalDependency(dep);
2018-02-25 09:00:20 +08:00
parser.state.module.buildInfo.strict = true;
}
});
};
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
2018-02-25 09:00:20 +08:00
}
);
}
}
module.exports = UseStrictPlugin;