webpack/lib/APIPlugin.js

91 lines
2.4 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
2013-01-31 01:49:25 +08:00
2018-07-03 16:24:29 +08:00
const {
toConstantDependency,
toConstantDependencyWithWebpackRequire,
evaluateToString
} = require("./JavascriptParserHelpers");
2018-11-03 04:05:46 +08:00
const NullFactory = require("./NullFactory");
const RuntimeGlobals = require("./RuntimeGlobals");
2018-07-30 23:08:51 +08:00
const ConstDependency = require("./dependencies/ConstDependency");
2018-11-03 04:05:46 +08:00
/** @typedef {import("./Compiler")} Compiler */
2013-01-31 01:49:25 +08:00
/* eslint-disable camelcase */
const REPLACEMENTS = {
__webpack_require__: "__webpack_require__",
__webpack_public_path__: RuntimeGlobals.publicPath,
__webpack_modules__: RuntimeGlobals.moduleFactories,
__webpack_chunk_load__: RuntimeGlobals.ensureChunk,
__non_webpack_require__: "require",
__webpack_nonce__: RuntimeGlobals.scriptNonce,
"require.onError": RuntimeGlobals.uncaughtErrorHandler
};
const NO_WEBPACK_REQUIRE = {
__non_webpack_require__: true
2013-01-31 01:49:25 +08:00
};
const REPLACEMENT_TYPES = {
__webpack_public_path__: "string",
__webpack_require__: "function",
__webpack_modules__: "object",
__webpack_chunk_load__: "function",
__webpack_nonce__: "string"
2013-07-11 05:20:07 +08:00
};
/* eslint-enable camelcase */
class APIPlugin {
2018-11-03 04:05:46 +08:00
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap(
"APIPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
2018-02-25 09:00:20 +08:00
const handler = parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.hooks.expression
.for(key)
.tap(
"APIPlugin",
NO_WEBPACK_REQUIRE[key]
2018-07-03 16:24:29 +08:00
? toConstantDependency(parser, REPLACEMENTS[key])
: toConstantDependencyWithWebpackRequire(
2018-02-25 09:00:20 +08:00
parser,
REPLACEMENTS[key]
2018-03-26 22:56:10 +08:00
)
2018-02-25 09:00:20 +08:00
);
parser.hooks.evaluateTypeof
.for(key)
2018-07-03 16:24:29 +08:00
.tap("APIPlugin", evaluateToString(REPLACEMENT_TYPES[key]));
2018-02-25 09:00:20 +08:00
});
};
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("APIPlugin", handler);
}
);
}
}
module.exports = APIPlugin;