/
index.js
95 lines (76 loc) · 2.79 KB
/
index.js
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
const paths = require('react-scripts/config/paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const defaultMinify = {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
};
function capitalize(str) {
return str ? str[0].toUpperCase() + str.substr(1, str.length) : '';
}
const replacePlugin = (plugins, nameMatcher, newPlugin) => {
const pluginIndex = plugins.findIndex((plugin) => {
return plugin.constructor && plugin.constructor.name && nameMatcher(plugin.constructor.name);
});
if (-1 === pluginIndex) {
return plugins;
}
const nextPlugins = plugins.slice(0, pluginIndex).concat(newPlugin).concat(plugins.slice(pluginIndex + 1));
return nextPlugins;
};
// params.entry
function createRewire(params) {
if (!params.entry || !params.entry.length) return; // todo: checkme!
const entries = [].concat(params.entry);
const bundles = entries.map(entry => {
const ext = entry.split('.').pop();
return entry.replace('.' + ext, '');
});
bundles.forEach((bundle, idx) => {
paths[`app${capitalize(bundle)}Js`] = `${paths.appSrc}/${entries[idx]}`;
});
function getHtmlPlugin(bundle, isProd) {
const opts = Object.assign({
inject: true,
template: paths.appHtml,
// note: 2.x adds optimization with 'vendors' and 'runtime~bundle' in chunks
chunks: ['vendors', 'runtime~' + bundle, bundle],
filename: bundle + '.html',
}, isProd ? { minify: Object.assign(defaultMinify, params.minify) } : {});
return new HtmlWebpackPlugin(opts);
}
return {
webpack: (config, env) => {
const isProd = env !== 'development';
config.entry = bundles.reduce((acc, bundle) => {
acc[bundle] = [].concat(
isProd ? [] : require.resolve('react-dev-utils/webpackHotDevClient'),
paths[`app${capitalize(bundle)}Js`]
);
return acc;
}, {});
config.output.filename = isProd ? 'static/js/[name].[chunkhash:8].js' : 'static/js/[name].bundle.js';
// initial HtmlWebpackPlugin for `index.html`
config.plugins = replacePlugin(config.plugins, (name) => /HtmlWebpackPlugin/i.test(name), getHtmlPlugin(bundles[0], isProd));
// HtmlWebpackPlugin for other *.html
bundles.slice(1).forEach(bundle => {
config.plugins.push(getHtmlPlugin(bundle, isProd));
});
return config;
},
devServer: (config) => {
config.historyApiFallback.rewrites = bundles.slice(1).map(bundle => {
return { from: new RegExp('^\/' + bundle + '.html'), to: `/build/${bundle}.html` }
});
return config;
}
};
}
module.exports = createRewire;