UNPKG

2.5 kBJavaScriptView Raw
1var path = require('path');
2var fs = require('fs');
3var glob = require('glob');
4var HtmlWebpackPlugin = require('html-webpack-plugin');
5
6var paths = require('./paths');
7
8function alphabetSort(a, b) {
9 if (a.names[0] === 'base') {
10 return -1;
11 }
12
13 if (b.names[0] === 'base') {
14 return 1;
15 }
16
17 if (a.names[0] > b.names[0]) {
18 return 1;
19 }
20
21 if (a.names[0] < b.names[0]) {
22 return -1;
23 }
24
25 return 0;
26}
27
28function buildEntryPointConfig(baseConfig) {
29 var entryPointConfig = baseConfig || {};
30 var appSrcPath = paths.appSrc;
31 var entryPointPaths = glob.sync('*.index.+(ts|tsx|js|tsx)', { cwd: appSrcPath });
32
33 return entryPointPaths.reduce(function(config, newPath) {
34 var entryPointName = path.basename(newPath).split('.')[0].toLowerCase();
35
36 config[entryPointName] = path.resolve(appSrcPath, newPath);
37
38 return config;
39 }, entryPointConfig);
40}
41
42function getIndexName(name) {
43 switch(name.toLowerCase()) {
44 case 'app':
45 return 'index.html';
46 case 'index':
47 return 'index.index.html';
48 default:
49 return name + '.html';
50 }
51}
52
53function buildHtmlWebpackPlugins(opts) {
54 var options = opts || {};
55 var entryPointConfig = Object.assign({}, options.entryPointConfig);
56 var isProduction = options.production || false;
57 var appPublicPath = paths.appPublic;
58 var appHtmlPath = paths.appHtml;
59
60 delete entryPointConfig.base;
61
62 return Object.keys(entryPointConfig).map(function(key) {
63 var indexFilename = getIndexName(key);
64 var customTemplatePath = path.resolve(appPublicPath, indexFilename);
65 var templatePath = fs.existsSync(customTemplatePath) ? customTemplatePath : appHtmlPath;
66
67 var customHtmlConfig = isProduction ? {
68 minify: {
69 removeComments: true,
70 collapseWhitespace: true,
71 removeRedundantAttributes: true,
72 useShortDoctype: true,
73 removeEmptyAttributes: true,
74 removeStyleLinkTypeAttributes: true,
75 keepClosingSlash: true,
76 minifyJS: true,
77 minifyCSS: true,
78 minifyURLs: true
79 }
80 } : {};
81
82 var htmlConfig = Object.assign(
83 {
84 inject: true,
85 chunks: ['base', key],
86 template: templatePath,
87 chunksSortMode: alphabetSort
88 },
89 customHtmlConfig,
90 {
91 filename: indexFilename
92 });
93
94 return new HtmlWebpackPlugin(htmlConfig);
95 });
96}
97
98module.exports = {
99 buildEntryPointConfig: buildEntryPointConfig,
100 buildHtmlWebpackPlugins: buildHtmlWebpackPlugins
101};