UNPKG

kef-builder-buffet

Version:

buffet-builder构建工具

64 lines (56 loc) 2.07 kB
'use strict'; // const ConcatSource = require('webpack/lib/ConcatSource'); module.exports = class WrapperPlugin { /** * WraperPlugin * @param {Object} options 选项 * @param {string|function} options.header 前内容 * @param {string|function} options.footer 后内容 * @constructor */ constructor(options) { this.header = options.hasOwnProperty('header') ? options.header : ''; this.footer = options.hasOwnProperty('footer') ? options.footer : ''; } apply(compiler) { const header = this.header; const footer = this.footer; const entry = compiler.options.entry; const wrapFile = (compilation, fileName) => { // chunks 在 apply SingleEntryPlugin 后会向 chunks push // 对应的当前模块, 根据模块的 name 也就是 entryName const headerContent = (typeof header === 'function') ? header(fileName, entry, compilation.chunks) : header; const footerContent = (typeof footer === 'function') ? footer(fileName, entry, compilation.chunks) : footer; const initSource = compilation.assets[fileName].source(); const resSource = `${String(headerContent)}${initSource}${String(footerContent)}`; // compilation.assets[fileName] = new ConcatSource( // String(headerContent), // compilation.assets[fileName], // String(footerContent)); compilation.assets[fileName] = { source() { // 写入文件时必写项 return resSource; }, size() { // 写入文件时必写项 return resSource.length } } }; const wrapChunks = (compilation, chunks) => { chunks.forEach((chunk) => { chunk.files.forEach((fileName) => { wrapFile(compilation, fileName); }); }); }; compiler.plugin('compilation', (compilation) => { // 优化 chunk 的生成资源 compilation.plugin('optimize-chunk-assets', (chunks, done) => { wrapChunks(compilation, chunks, footer, header); done(); }); }); } };