UNPKG

@sanpjs/bundler-webpack

Version:

@sanpjs/bundler-webpack

87 lines 3.32 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getHtmlWebpackPlugin = void 0; const html_webpack_plugin_1 = __importDefault(require("html-webpack-plugin")); const html_tags_1 = require("html-webpack-plugin/lib/html-tags"); const genAttrs = (attrs) => { return attrs && Object.keys(attrs).reduce((res, key) => `${res} ${key}=${attrs[key]}`, ''); }; const createTags = (tags = []) => { const res = tags.map((tag) => { const element = (0, html_tags_1.createHtmlTagObject)(tag.tagName, tag.attributes, tag.innerHTML); return (0, html_tags_1.htmlTagObjectToString)(element); }); return res.join(''); }; const getHtmlWebpackPlugin = (context, isSsr) => { const { pages, build: { optimization } } = context.config; const htmlOptions = { inject: true, minify: false }; if (context.prod) { htmlOptions.minify = optimization.htmlMinify; } const htmlPlugin = []; pages.forEach((p) => { let pageConfig = p; let { name: entry, template = context.getLayout(entry), filename, // 这里需要跟 mode 里面的 splitChunks 遥相呼应 chunks = [entry], title, html = {}, head = {}, body = {} } = pageConfig; if (Array.isArray(chunks) && chunks.indexOf(entry) === -1) { chunks.push(entry); } if (!filename) { filename = `${entry}.html`; } if (isSsr && typeof filename === 'string') { // 避免二次打包模板文件被覆盖 filename = 'server.' + filename; } // inject html plugin for the page const pageHtmlOptions = { alwaysWriteToDisk: true, scriptLoading: 'blocking', ...htmlOptions, entry, chunks, template, filename, title, templateParameters: (compilation, assets, assetTags, opt) => { // html-webpack-plugin version>=4 let stats; return Object.assign({ // lazy get stats() { return stats || (stats = compilation.getStats().toJson()); }, compilation, webpackConfig: compilation.options, // sanp context context, title, htmlAttrs: genAttrs(html.attributes), headAttrs: genAttrs(head.attributes), headTags: createTags(head.tags), bodyAttrs: genAttrs(body.attributes), bodyTags: createTags(body.tags), htmlWebpackPlugin: { files: assets, tags: assetTags, options: { ...opt } } }); } }; htmlPlugin.push(new html_webpack_plugin_1.default(pageHtmlOptions)); }); return htmlPlugin; }; exports.getHtmlWebpackPlugin = getHtmlWebpackPlugin; //# sourceMappingURL=html.js.map