HtmlGenerator.js 4.06 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { cheerio } = require('@umijs/utils');
class MyPlugin {
  constructor(opts) {
    this.opts = opts;
  }

  getAsset(opts) {
    if (/^(https|http)?:\/\//.test(opts.file)) {
      return opts.file;
    }
    // const file = opts.file.charAt(0) === '/' ? opts.file.slice(1) : opts.file;
    // return `${this.config.publicPath}${file}`;
  }

  getStyles(option) {
    const linkArr = [];
    const styleObj = [];
    if (Array.isArray(option) && option.length > 0) {
      option.forEach(style => {
        if (typeof style === 'string') {
          if (EXP_URL.test(style)) {
            // is <link />
            linkArr.push({
              charset: 'utf-8',
              rel: 'stylesheet',
              type: 'text/css',
              href: style,
            });
          } else {
            styleObj.push({
              content: style,
            });
          }
        }
        if (typeof style === 'object') {
          // is style object
          styleObj.push(style);
        }
      });
    }
    return [linkArr, styleObj];
  }

  getScriptsContent(scripts) {
    return scripts
      .map(script => {
        const { content, ...attrs } = script;
        if (content && !attrs.src) {
          const newAttrs = Object.keys(attrs).reduce((memo, key) => {
            return [...memo, `${key}="${attrs[key]}"`];
          }, []);
          return [
            `<script${newAttrs.length ? ' ' : ''}${newAttrs.join(' ')}>`,
            content
              .split('\n')
              .map(line => `  ${line}`)
              .join('\n'),
            '</script>',
          ].join('\n');
        } else {
          const newAttrs = Object.keys(attrs).reduce((memo, key) => {
            return [...memo, `${key}="${attrs[key]}"`];
          }, []);
          return `<script ${newAttrs.join(' ')}></script>`;
        }
      })
      .join('\n');
  }

  getContent(html, config) {
    let {
      metas = [],
      links = [],
      headScripts = [],
      scripts = [],
    } = config;

    const $ = cheerio.load(html, {
      decodeEntities: false,
    });
    metas.forEach(meta => {
      $('head').append(
        [
          '<meta',
          ...Object.keys(meta).reduce((memo, key) => {
            return memo.concat(`${key}="${meta[key]}"`);
          }, []),
          '/>',
        ].join(' '),
      );
    });

    links.forEach(link => {
      $('head').append(
        [
          '<link',
          ...Object.keys(link).reduce((memo, key) => {
            return memo.concat(`${key}="${link[key]}"`);
          }, []),
          '/>',
        ].join(' '),
      );
    });

    const [linkArr = [], styleArr = []] = this.getStyles(this.opts.config.styles);
    styleArr.forEach(style => {
      const { content = '', ...attrs } = style;
      const newAttrs = Object.keys(attrs).reduce((memo, key) => {
        return memo.concat(`${key}="${attrs[key]}"`);
      }, []);
      $('head').append(
        [
          `<style${newAttrs.length ? ' ' : ''}${newAttrs.join(' ')}>`,
          content
            .split('\n')
            .map(line => `  ${line}`)
            .join('\n'),
          '</style>',
        ].join('\n'),
      );
    });

    if (headScripts.length) {
      $('head').append(this.getScriptsContent(headScripts));
    }

    if (scripts.length) {
      $('body').append(this.getScriptsContent(scripts));
    }

    linkArr.forEach(file => {
      $('head').append(
        `<link rel="stylesheet" href="${this.getAsset({
          file: file.href,
        })}" />`,
      );
    });

    html = $.html();
    return html; 
  }

  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', compilation => {
      HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapAsync(
        'MyPlugin', // <-- Set a meaningful name here for stacktraces
        (data, cb) => {
          if (data && data.html !== '') {
            data.html = this.getContent(data.html, this.opts.config);
          }
          // Tell webpack to move on
          cb(null, data);
        },
      );
    });
  }
}

module.exports = MyPlugin;