webpack/lib/DefinePlugin.js

283 lines
7.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
"use strict";
const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
2018-07-03 16:24:29 +08:00
const {
approve,
evaluateToString,
2018-11-06 02:03:12 +08:00
toConstantDependency
} = require("./JavascriptParserHelpers");
2018-11-06 02:03:12 +08:00
const RuntimeGlobals = require("./RuntimeGlobals");
2018-07-30 23:08:51 +08:00
const ConstDependency = require("./dependencies/ConstDependency");
/** @typedef {import("./Compiler")} Compiler */
2018-07-17 17:32:15 +08:00
/** @typedef {import("./JavascriptParser")} JavascriptParser */
2018-07-13 09:06:21 +08:00
/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */
/** @typedef {CodeValuePrimitive|Record<string, CodeValuePrimitive>|RuntimeValue} CodeValue */
class RuntimeValue {
constructor(fn, fileDependencies) {
this.fn = fn;
this.fileDependencies = fileDependencies || [];
}
exec(parser) {
const buildInfo = parser.state.module.buildInfo;
if (this.fileDependencies === true) {
buildInfo.cacheable = false;
} else {
for (const fileDependency of this.fileDependencies) {
buildInfo.fileDependencies.add(fileDependency);
if (!buildInfo.snapshot.fileTimestamps.has(fileDependency))
buildInfo.snapshot.fileTimestamps.set(fileDependency, {});
}
}
return this.fn({ module: parser.state.module });
}
}
const stringifyObj = (obj, parser) => {
2018-02-25 09:00:20 +08:00
return (
"Object({" +
Object.keys(obj)
.map(key => {
const code = obj[key];
return JSON.stringify(key) + ":" + toCode(code, parser);
2018-02-25 09:00:20 +08:00
})
.join(",") +
"})"
);
2017-11-08 18:32:05 +08:00
};
2018-05-20 15:32:59 +08:00
/**
* Convert code to a string that evaluates
2018-06-23 05:17:55 +08:00
* @param {CodeValue} code Code to evaluate
2018-07-17 17:32:15 +08:00
* @param {JavascriptParser} parser Parser
2018-05-20 15:32:59 +08:00
* @returns {string} code converted to string that evaluates
*/
const toCode = (code, parser) => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (code instanceof RuntimeValue) {
return toCode(code.exec(parser), parser);
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
2018-02-25 09:00:20 +08:00
return "(" + code.toString() + ")";
}
if (typeof code === "object") {
return stringifyObj(code, parser);
}
return code + "";
2017-11-08 18:32:05 +08:00
};
class DefinePlugin {
2018-05-20 15:32:59 +08:00
/**
* Create a new define plugin
2018-07-13 09:06:21 +08:00
* @param {Record<string, CodeValue>} definitions A map of global object definitions
2018-05-20 15:32:59 +08:00
*/
constructor(definitions) {
this.definitions = definitions;
}
2015-07-13 06:20:09 +08:00
static runtimeValue(fn, fileDependencies) {
return new RuntimeValue(fn, fileDependencies);
}
2018-05-20 15:32:59 +08:00
/**
* Apply the plugin
* @param {Compiler} compiler Webpack compiler
2018-06-10 10:37:09 +08:00
* @returns {void}
2018-05-20 15:32:59 +08:00
*/
apply(compiler) {
const definitions = this.definitions;
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap(
"DefinePlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
2015-07-13 06:20:09 +08:00
2018-05-20 15:32:59 +08:00
/**
* Handler
2018-07-17 17:32:15 +08:00
* @param {JavascriptParser} parser Parser
2018-06-10 10:37:09 +08:00
* @returns {void}
2018-05-20 15:32:59 +08:00
*/
2018-02-25 09:00:20 +08:00
const handler = parser => {
2018-06-10 10:37:09 +08:00
/**
* Walk definitions
2018-06-23 05:17:55 +08:00
* @param {Object} definitions Definitions map
2018-06-10 10:37:09 +08:00
* @param {string} prefix Prefix string
* @returns {void}
*/
2018-02-25 09:00:20 +08:00
const walkDefinitions = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
const code = definitions[key];
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
2018-02-25 09:00:20 +08:00
!(code instanceof RegExp)
) {
walkDefinitions(code, prefix + key + ".");
applyObjectDefine(prefix + key, code);
return;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
});
};
2015-07-13 06:20:09 +08:00
2018-05-20 15:32:59 +08:00
/**
* Apply define key
* @param {string} prefix Prefix
* @param {string} key Key
2018-06-10 10:37:09 +08:00
* @returns {void}
2018-05-20 15:32:59 +08:00
*/
2018-02-25 09:00:20 +08:00
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
splittedKey.slice(1).forEach((_, i) => {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
2018-07-03 16:24:29 +08:00
parser.hooks.canRename.for(fullKey).tap("DefinePlugin", approve);
2018-02-25 09:00:20 +08:00
});
};
2018-05-20 15:32:59 +08:00
/**
* Apply Code
* @param {string} key Key
2018-06-23 05:17:55 +08:00
* @param {CodeValue} code Code
2018-06-10 10:37:09 +08:00
* @returns {void}
2018-05-20 15:32:59 +08:00
*/
2018-02-25 09:00:20 +08:00
const applyDefine = (key, code) => {
const isTypeof = /^typeof\s+/.test(key);
if (isTypeof) key = key.replace(/^typeof\s+/, "");
let recurse = false;
let recurseTypeof = false;
if (!isTypeof) {
2018-07-03 16:24:29 +08:00
parser.hooks.canRename.for(key).tap("DefinePlugin", approve);
2018-02-25 09:00:20 +08:00
parser.hooks.evaluateIdentifier
.for(key)
.tap("DefinePlugin", expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "a": "b",
* "b": "a"
* });
*/
if (recurse) return;
recurse = true;
const res = parser.evaluate(toCode(code, parser));
2018-02-25 09:00:20 +08:00
recurse = false;
res.setRange(expr.range);
return res;
});
parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
const strCode = toCode(code, parser);
if (/__webpack_require__/.test(strCode)) {
2018-11-06 02:03:12 +08:00
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else {
2018-07-05 04:08:31 +08:00
return toConstantDependency(parser, strCode)(expr);
}
});
2018-02-25 09:00:20 +08:00
}
parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
2018-02-26 10:49:41 +08:00
* "typeof a": "typeof b",
2018-02-25 09:00:20 +08:00
* "typeof b": "typeof a"
* });
*/
2018-02-25 09:00:20 +08:00
if (recurseTypeof) return;
recurseTypeof = true;
const typeofCode = isTypeof
? toCode(code, parser)
: "typeof (" + toCode(code, parser) + ")";
2018-02-25 09:00:20 +08:00
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(expr.range);
return res;
});
2018-02-25 09:00:20 +08:00
parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
const typeofCode = isTypeof
? toCode(code, parser)
: "typeof (" + toCode(code, parser) + ")";
2018-02-25 09:00:20 +08:00
const res = parser.evaluate(typeofCode);
if (!res.isString()) return;
2018-07-03 16:24:29 +08:00
return toConstantDependency(
2018-02-25 09:00:20 +08:00
parser,
JSON.stringify(res.string)
).bind(parser)(expr);
});
};
2018-05-20 15:32:59 +08:00
/**
* Apply Object
* @param {string} key Key
* @param {Object} obj Object
2018-06-10 10:37:09 +08:00
* @returns {void}
2018-05-20 15:32:59 +08:00
*/
2018-02-25 09:00:20 +08:00
const applyObjectDefine = (key, obj) => {
2018-07-03 16:24:29 +08:00
parser.hooks.canRename.for(key).tap("DefinePlugin", approve);
2018-02-25 09:00:20 +08:00
parser.hooks.evaluateIdentifier
.for(key)
.tap("DefinePlugin", expr =>
new BasicEvaluatedExpression().setTruthy().setRange(expr.range)
);
parser.hooks.evaluateTypeof
.for(key)
2018-07-03 16:24:29 +08:00
.tap("DefinePlugin", evaluateToString("object"));
parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
const strCode = stringifyObj(obj, parser);
if (/__webpack_require__/.test(strCode)) {
2018-11-06 02:03:12 +08:00
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
2018-07-05 04:08:31 +08:00
} else {
return toConstantDependency(parser, strCode)(expr);
}
});
2018-02-25 09:00:20 +08:00
parser.hooks.typeof
.for(key)
.tap(
"DefinePlugin",
2018-07-03 16:24:29 +08:00
toConstantDependency(parser, JSON.stringify("object"))
2018-02-25 09:00:20 +08:00
);
};
2017-11-08 18:32:05 +08:00
2018-02-25 09:00:20 +08:00
walkDefinitions(definitions, "");
};
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("DefinePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("DefinePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("DefinePlugin", handler);
}
);
}
}
module.exports = DefinePlugin;