@zohodesk/client_build_tool
Version:
A CLI tool to build web applications and client libraries
98 lines (81 loc) • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InitialHtmlPlugin = void 0;
var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'InitialHtmlPlugin';
class InitialHtmlPlugin {
constructor(options) {
this.options = options;
}
getBaseName(str) {
const fileName = str.split("/").pop();
const parts = fileName.split("."); // Find index of the hash-like segment
const hashIndex = parts.findIndex(p => /^[0-9a-f_]{20,}$/i.test(p)); // If a hash is found, return everything before it
if (hashIndex < 0) {
console.error('this initial file dont have a hash');
return parts.slice(0, -1).join(".");
}
return parts.slice(0, hashIndex).join("."); // Otherwise fallback: remove only ".js"
}
apply(compiler) {
const {
filename,
template,
minify,
inject,
mainChunkName,
enableSubResourceIntegrity
} = this.options;
new _htmlWebpackPlugin.default({
filename,
template,
minify,
chunks: [mainChunkName],
inject,
scriptLoading: 'defer'
}).apply(compiler);
compiler.hooks.thisCompilation.tap(pluginName, compilation => {
_htmlWebpackPlugin.default.getHooks(compilation).alterAssetTagGroups.tapAsync(pluginName, (data, cb) => {
const headTags = [];
const bodyTags = [];
data.headTags.forEach(tag => {
const url = tag.attributes?.src || tag.attributes?.href;
let chunkName;
const addIntegrity = (tag, suffix) => {
if (enableSubResourceIntegrity && chunkName) {
Object.assign(tag.attributes, {
integrity: `{{--${chunkName}-${suffix}-integrity}}`
});
}
};
if (enableSubResourceIntegrity) {
chunkName = this.getBaseName(url);
}
Object.assign(tag.attributes, {
nonce: '{{--CSP-nonce}}',
crossorigin: "anonymous"
});
if (tag.tagName === 'link') {
addIntegrity(tag, 'css');
headTags.push(tag);
} else {
if (url.endsWith('.i18n.js')) {
addIntegrity(tag, 'i18n');
} else {
addIntegrity(tag, 'js');
}
bodyTags.push(tag);
}
});
cb(null, { ...data,
headTags,
bodyTags
});
});
});
}
}
exports.InitialHtmlPlugin = InitialHtmlPlugin;