@zohodesk/client_build_tool
Version:
A CLI tool to build web applications and client libraries
89 lines (70 loc) • 2.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _SingleEntryPlugin = _interopRequireDefault(require("webpack/lib/SingleEntryPlugin.js"));
var _nameTemplates = require("../../common/nameTemplates");
var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'MurphyInjectorPlugin';
class MurphyInjectorPlugin {
constructor(entries = [], options) {
this.entries = entries;
this.options = options;
this.jsTemplate = options.cdnMapping.jsTemplate || '{{__JS_CDN__}}';
this.cdnMapping = options.cdnMapping;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(pluginName, compilation => {
this.entries.forEach(({
name,
file
}) => {
// Create child compiler for this entry
const childCompiler = compilation.createChildCompiler(`additional-entry ${name}`, {
filename: (0, _nameTemplates.nameTemplates)('js', this.options),
// output filename
chunkFilename: `${name}.[id].js`,
publicPath: compiler.options.output.publicPath,
globalObject: "self" // safe for workers too
}); // Attach the entry point
new _SingleEntryPlugin.default(compiler.context, file, name).apply(childCompiler); // Run the child compiler
childCompiler.runAsChild((err, entries, childCompilation) => {
if (err) {
compilation.errors.push(err);
return;
}
if (childCompilation.errors && childCompilation.errors.length) {
compilation.errors.push(...childCompilation.errors);
} // Files are emitted automatically by child compiler
// ⚡ Hook HtmlWebpackPlugin and inject this file
_htmlWebpackPlugin.default.getHooks(compilation).alterAssetTags.tapAsync(pluginName, (data, cb) => {
let fileName = '';
const childFiles = childCompilation.entrypoints.get(name).getFiles();
if (childFiles.length !== 1) {
compilation.errors.push(new Error(`${pluginName}: Expected exactly 1 child file for entry "${name}", but got ${childFiles.length}.`));
}
if (this.cdnMapping.isCdnEnabled) {
fileName = `${this.jsTemplate}${childFiles[0]}`;
}
;
data.assetTags.scripts.unshift({
tagName: "script",
voidTag: false,
attributes: {
src: fileName
},
meta: {
plugin: pluginName
}
});
cb(null, data);
});
});
});
});
}
}
var _default = MurphyInjectorPlugin;
exports.default = _default;