webpack/lib/dependencies/CachedConstDependency.js

76 lines
2.4 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
"use strict";
2018-07-27 17:45:12 +08:00
const DependencyTemplate = require("../DependencyTemplate");
const InitFragment = require("../InitFragment");
const NullDependency = require("./NullDependency");
2018-07-27 17:45:12 +08:00
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").TemplateContext} TemplateContext */
2018-07-27 17:45:12 +08:00
/** @typedef {import("../DependencyTemplates")} DependencyTemplates */
/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("../util/createHash").Hash} Hash */
class CachedConstDependency extends NullDependency {
constructor(expression, range, identifier) {
super();
this.expression = expression;
this.range = range;
this.identifier = identifier;
}
2018-07-27 17:45:12 +08:00
/**
* Update the hash
* @param {Hash} hash hash to be updated
* @returns {void}
*/
updateHash(hash) {
hash.update(this.identifier + "");
hash.update(this.range + "");
hash.update(this.expression + "");
}
}
2018-07-27 17:45:12 +08:00
CachedConstDependency.Template = class CachedConstDependencyTemplate extends DependencyTemplate {
/**
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {DependencyTemplates} dependencyTemplates the dependency templates
* @returns {void}
*/
apply(dependency, source, runtimeTemplate, dependencyTemplates) {
const dep = /** @type {CachedConstDependency} */ (dependency);
if (typeof dep.range === "number") {
source.insert(dep.range, dep.identifier);
return;
}
source.replace(dep.range[0], dep.range[1] - 1, dep.identifier);
}
2018-07-27 17:45:12 +08:00
/**
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {TemplateContext} templateContext the template context
2018-07-27 17:45:12 +08:00
* @returns {InitFragment[]|null} the init fragments
*/
getInitFragments(dependency, { runtimeTemplate, dependencyTemplates }) {
2018-07-27 17:45:12 +08:00
const dep = /** @type {CachedConstDependency} */ (dependency);
return [
new InitFragment(
2018-07-27 17:45:12 +08:00
`var ${dep.identifier} = ${dep.expression};\n`,
2018-07-30 16:15:18 +08:00
InitFragment.STAGE_CONSTANTS,
0,
2018-07-27 17:45:12 +08:00
`const ${dep.identifier}`
)
];
}
};
module.exports = CachedConstDependency;