1 | const path = require('path');
|
2 | const { RawSource } = require('webpack-sources');
|
3 |
|
4 | class MiniHtmlWebpackPlugin {
|
5 | constructor(options = {}) {
|
6 | this.options = options;
|
7 | }
|
8 | apply(compiler) {
|
9 | const { filename, template, context } = this.options;
|
10 |
|
11 | compiler.plugin('emit', (compilation, cb) => {
|
12 | const { publicPath } = compilation.options.output;
|
13 | const files = getFiles(normalizeEntrypoints(compilation.entrypoints));
|
14 |
|
15 | compilation.assets[filename || 'index.html'] = new RawSource(
|
16 | (template || defaultTemplate)(
|
17 | Object.assign({}, { publicPath }, context, files)
|
18 | )
|
19 | );
|
20 |
|
21 | cb();
|
22 | });
|
23 | }
|
24 | }
|
25 |
|
26 | function getFiles(entrypoints) {
|
27 | const ret = {};
|
28 |
|
29 | entrypoints.forEach(entry => {
|
30 | entry.getFiles().forEach(file => {
|
31 | const extension = path.extname(file).replace(/\./, '');
|
32 |
|
33 | if (!ret[extension]) {
|
34 | ret[extension] = [];
|
35 | }
|
36 |
|
37 | ret[extension].push(file);
|
38 | });
|
39 | });
|
40 |
|
41 | return ret;
|
42 | }
|
43 |
|
44 | function normalizeEntrypoints(entrypoints) {
|
45 |
|
46 | if (entrypoints.forEach) {
|
47 | return entrypoints;
|
48 | }
|
49 |
|
50 |
|
51 | return Object.keys(entrypoints).map(name => entrypoints[name]);
|
52 | }
|
53 |
|
54 | function defaultTemplate({ css, js, title = '', publicPath }) {
|
55 | return `<!DOCTYPE html>
|
56 | <html>
|
57 | <head>
|
58 | <meta charset="UTF-8">
|
59 | <title>${title}</title>
|
60 |
|
61 | ${generateCSSReferences(css, publicPath)}
|
62 | </head>
|
63 | <body>
|
64 | ${generateJSReferences(js, publicPath)}
|
65 | </body>
|
66 | </html>`;
|
67 | }
|
68 |
|
69 | function generateCSSReferences(files = [], publicPath = '') {
|
70 | return files
|
71 | .map(file => `<link href="${publicPath}${file}" rel="stylesheet">`)
|
72 | .join('');
|
73 | }
|
74 |
|
75 | function generateJSReferences(files = [], publicPath = '') {
|
76 | return files
|
77 | .map(file => `<script src="${publicPath}${file}"></script>`)
|
78 | .join('');
|
79 | }
|
80 |
|
81 | module.exports = MiniHtmlWebpackPlugin;
|
82 | module.exports.defaultTemplate = defaultTemplate;
|
83 | module.exports.generateCSSReferences = generateCSSReferences;
|
84 | module.exports.generateJSReferences = generateJSReferences;
|