Skip to content

Commit

Permalink
refactor: reduce runtime code
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-akait committed Jul 25, 2024
1 parent c3faac4 commit 142ac35
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 31 deletions.
4 changes: 1 addition & 3 deletions src/plugins/sources-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ export default (options) =>
let offset = 0;

for (const source of sources) {
const { name, value, isValueQuoted, runtime, startOffset, endOffset } =
source;
const { name, value, isValueQuoted, startOffset, endOffset } = source;

let request = value;

Expand Down Expand Up @@ -180,7 +179,6 @@ export default (options) =>
importName,
hash,
isValueQuoted,
runtime,
});
}

Expand Down
47 changes: 19 additions & 28 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -1268,37 +1268,28 @@ export function getModuleCode(html, replacements, loaderContext, options) {
let needHelperImport = false;

for (const item of replacements) {
const { runtime, importName, replacementName, isValueQuoted, hash } = item;

if (typeof runtime === "undefined" || runtime === true) {
const getUrlOptions = []
.concat(hash ? [`hash: ${JSON.stringify(hash)}`] : [])
.concat(isValueQuoted ? [] : "maybeNeedQuotes: true");
const preparedOptions =
getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";

const needHelperFn = getUrlOptions.length > 0;

if (needHelperFn) {
if (!needHelperImport) {
needHelperImport = true;
}

replacersCode += `var ${replacementName} = ${GET_SOURCE_FROM_IMPORT_NAME}(${importName}${preparedOptions});\n`;
const { importName, replacementName, isValueQuoted, hash } = item;
const getUrlOptions = []
.concat(hash ? [`hash: ${JSON.stringify(hash)}`] : [])
.concat(isValueQuoted ? [] : "maybeNeedQuotes: true");
const preparedOptions =
getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";

const needHelperFn = getUrlOptions.length > 0;

if (needHelperFn) {
if (!needHelperImport) {
needHelperImport = true;
}

const name = needHelperFn ? replacementName : importName;

code = code.replace(new RegExp(replacementName, "g"), () =>
isTemplateLiteralSupported ? `\${${name}}` : `" + ${name} + "`,
);
} else {
code = code.replace(new RegExp(replacementName, "g"), () =>
isTemplateLiteralSupported
? `\${${replacementName}}`
: `" + ${replacementName} + "`,
);
replacersCode += `var ${replacementName} = ${GET_SOURCE_FROM_IMPORT_NAME}(${importName}${preparedOptions});\n`;
}

const name = needHelperFn ? replacementName : importName;

code = code.replace(new RegExp(replacementName, "g"), () =>
isTemplateLiteralSupported ? `\${${name}}` : `" + ${name} + "`,
);
}

// Replaces "<script>" or "</script>" to "<" + "script>" or "<" + "/script>".
Expand Down

0 comments on commit 142ac35

Please sign in to comment.