MCPcopy
hub / github.com/ampproject/amphtml / getReplacePlugin

Function getReplacePlugin

build-system/babel-config/helpers.js:33–83  ·  view source on GitHub ↗

* Computes options for minify-replace and returns the plugin object. * * @param {!Object=} opt_overrides overrides for BUILD_CONSTANTS * @return {Array }

(opt_overrides)

Source from the content-addressed store, hash-verified

31 * @return {Array<string|Object>}
32 */
33function getReplacePlugin(opt_overrides) {
34 /**
35 * @param {string} identifierName the identifier name to replace
36 * @param {boolean|string} value the value to replace with
37 * @return {!Object} replacement options used by minify-replace plugin
38 */
39 function createReplacement(identifierName, value) {
40 const replacement =
41 typeof value === 'boolean'
42 ? {type: 'booleanLiteral', value}
43 : {type: 'stringLiteral', value};
44 return {identifierName, replacement};
45 }
46
47 const constants = Object.assign({}, BUILD_CONSTANTS, opt_overrides);
48 const replacements = Object.entries(constants).map(([ident, val]) =>
49 createReplacement(ident, val)
50 );
51
52 const experimentConstant = getExperimentConstant();
53 if (experimentConstant) {
54 replacements.push(createReplacement(experimentConstant, true));
55 }
56
57 // default each experiment flag constant to false
58 Object.keys(experimentsConfig).forEach((experiment) => {
59 const experimentDefine =
60 experimentsConfig[experiment]['define_experiment_constant'];
61 const flagExists = (element) =>
62 element['identifierName'] === experimentDefine;
63 // only add default replacement if it already doesn't exist in array
64 if (experimentDefine && !replacements.some(flagExists)) {
65 replacements.push(createReplacement(experimentDefine, false));
66 }
67 });
68
69 // default each backup experiment constant to the customized value
70 const experimentsConstantBackupEntries = Object.entries(
71 experimentsConstantBackup
72 );
73 for (const [experimentDefine, value] of experimentsConstantBackupEntries) {
74 const flagExists = (element) =>
75 element['identifierName'] === experimentDefine;
76 // only add default replacement if it already doesn't exist in array
77 if (experimentDefine && !replacements.some(flagExists)) {
78 replacements.push(createReplacement(experimentDefine, !!value));
79 }
80 }
81
82 return ['minify-replace', {replacements}];
83}
84
85/**
86 * Returns a Babel plugin that replaces the global identifier with the correct

Callers 3

getTestConfigFunction · 0.85
getMinifiedConfigFunction · 0.85
getUnminifiedConfigFunction · 0.85

Calls 6

createReplacementFunction · 0.85
getExperimentConstantFunction · 0.85
assignMethod · 0.80
entriesMethod · 0.45
pushMethod · 0.45
forEachMethod · 0.45

Tested by

no test coverage detected