webpack/lib/APIPlugin.js

106 lines
2.5 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,
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 = {
2018-11-06 02:03:12 +08:00
__webpack_require__: {
expr: RuntimeGlobals.require,
req: [RuntimeGlobals.require],
type: "function"
},
__webpack_public_path__: {
expr: RuntimeGlobals.publicPath,
req: [RuntimeGlobals.publicPath],
type: "string"
},
__webpack_modules__: {
expr: RuntimeGlobals.moduleFactories,
req: [RuntimeGlobals.moduleFactories],
type: "object"
},
__webpack_chunk_load__: {
expr: RuntimeGlobals.ensureChunk,
req: [RuntimeGlobals.ensureChunk],
type: "function"
},
__non_webpack_require__: {
expr: "require",
req: null,
type: undefined
},
__webpack_nonce__: {
expr: RuntimeGlobals.scriptNonce,
req: [RuntimeGlobals.scriptNonce],
type: "string"
},
"require.onError": {
expr: RuntimeGlobals.uncaughtErrorHandler,
req: [RuntimeGlobals.uncaughtErrorHandler],
type: "function"
}
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 => {
2018-11-06 02:03:12 +08:00
const info = REPLACEMENTS[key];
2018-02-25 09:00:20 +08:00
parser.hooks.expression
.for(key)
.tap(
"APIPlugin",
2018-11-06 02:03:12 +08:00
toConstantDependency(parser, info.expr, info.req)
2018-02-25 09:00:20 +08:00
);
2018-11-06 02:03:12 +08:00
if (info.type) {
parser.hooks.evaluateTypeof
.for(key)
.tap("APIPlugin", evaluateToString(info.type));
}
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;