/
webpack.js
294 lines (266 loc) · 9.3 KB
/
webpack.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
const path = require('path');
const fsExtra = require('fs-extra');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const clone = require('clone');
const { pascalCase } = require('change-case');
const { getTagHTMLFromEntry } = require('./tags');
const { getBuildDir, MODULE_NAME, getDefaultWebpackOutputOptions } = require('./index');
function webpackBuild (config) {
return new Promise((resolve) => {
webpack(config, (err, stats) => {
if (err || stats.hasErrors()) {
throw err;
}
resolve(stats);
});
});
}
async function processBuilds (webpackConfigs, statsList = []) {
const configs = webpackConfigs.splice(0, Math.min(1, webpackConfigs.length));
if (configs.length > 0) {
const stats = await Promise.all(configs.map(async config => ({ name: Object.keys(config.entry)[0], stats: await webpackBuild(config) })));
return processBuilds(webpackConfigs, statsList.concat(stats));
} else {
return statsList;
}
}
function build (webpackConfigs, nuxt) {
const builds = processBuilds(webpackConfigs.flat());
return builds.then((statsList) => {
const releases = statsList.reduce((result, { name, stats }) => {
const data = getJSFilesFromStats(stats);
result[String(name)] = Object.assign({}, result[String(name)], { [data.name]: data });
return result;
}, {});
return Promise.all(Object.keys(releases).map((name) => {
const content = JSON.stringify(releases[String(name)]);
const filepath = path.resolve(getBuildDir(nuxt), name, 'release.json');
return fsExtra.writeFile(filepath, content, 'utf-8');
}));
}).catch((err) => {
throw err;
});
}
function setLoaderRulesForShadowMode (rules) {
const vueLoaderRule = rules.find(({ test }) => test.test('.vue'));
if (vueLoaderRule) {
vueLoaderRule.options.shadowMode = true;
} else {
throw new Error('Can\'t find `vue-loader`…');
}
const ruleSets = ['css', 'postcss', 'scss', 'sass', 'less', 'stylus'];
const vueStyleLoaderDefinitions = ruleSets.reduce((result, name) => [
...result,
rules
.find(({ test }) => test.test(`.${name}`))], [])
.filter(Boolean)
.map((v) => {
if ('oneOf' in v) {
const one = v.oneOf.find(v => Object.keys(v).length === 1);
if (one && 'use' in one) {
return one.use[0];
}
}
return null;
});
if (vueStyleLoaderDefinitions.length) {
vueStyleLoaderDefinitions.forEach(({ options }) => (options.shadowMode = true));
} else {
throw new Error('Can\'t find `vue-style-loader` rules…');
}
return rules;
}
async function getWebpackConfig (entryName, nuxt, config, options) {
const isModernBuild = config.name === 'modern';
const buildDir = path.normalize(path.join(getBuildDir(nuxt), entryName));
const pluginExcludes = [
'VueSSRClientPlugin', 'CorsPlugin', 'HtmlWebpackPlugin', 'BundleAnalyzerPlugin',
// Remove all native Objects, PWA Modul registriert sich ohne identifizierbares Object (PWA)
'Object'
];
const htmlWebpackPluginIndex = config.plugins.indexOf(config.plugins.find(plugin => plugin.constructor.name === 'HtmlWebpackPlugin'));
let rules = clone(config.module.rules);
if (options.entries.find(({ name }) => name === entryName).shadow) {
rules = setLoaderRulesForShadowMode(rules);
}
rules = fixCSSLoaderRulesForExtractCSS(nuxt, rules);
// ModernModePlugin
const plugins = config.plugins.reduce((result, plugin) => {
if (!pluginExcludes.includes(plugin.constructor.name)) {
result.push(...pluginReplace(plugin, {
ModernModePlugin: {
targetDir: buildDir,
isModernBuild
}
}));
}
return result;
}, []);
plugins.splice(htmlWebpackPluginIndex, 0, ...createHtmlWebpackPlugins(options.entries.filter(({ name }) => entryName === name), options.publicPath));
plugins.push(...getBundleAnalyzerPlugin(options, config, entryName));
const output = getDefaultWebpackOutputOptions();
const { filename, chunkFilename } = output;
const webpackExtend = options.entries.find(({ name }) => name === entryName).webpackExtend || (config => config);
return await webpackExtend(Object.assign({}, config, {
target: 'web',
entry: prepareEntries(config, options, isModernBuild),
output: Object.assign(output, {
filename: resolveFilename(filename, config, options),
chunkFilename: resolveFilename(chunkFilename, config, options),
path: buildDir,
jsonpFunction: getJsonPFunctionName(entryName)
}),
optimization: {
runtimeChunk: false
},
plugins,
module: {
...config.module,
rules
}
}), { client: !isModernBuild, modern: isModernBuild });
}
function getJsonPFunctionName (entryName) {
return 'webpackJsonpNuxtCustomElements' + pascalCase(entryName);
}
function resolveFilename (filename, config, options) {
if (typeof filename === 'function') {
return filename(config, options);
}
return filename;
}
function prepareEntries (config, options, isModernBuild) {
return Object.fromEntries(Object.keys(options.entry).map((key) => {
const files = config.entry.app.map((file) => {
if (file.endsWith('client.js')) {
return options.entry[String(key)][isModernBuild ? 'modern' : 'client'];
}
return file;
});
return [key, files];
}));
}
function getBundleAnalyzerPlugin (options, config, entryName) {
// BundleAnalyzerPlugin
if (options.analyzer) {
const analyzerOptions = Object.assign({
reportFilename: path.resolve(`.reports/webpack/${MODULE_NAME}/${entryName}/${config.name}.html`),
statsFilename: path.resolve(`.reports/webpack/${MODULE_NAME}/${entryName}/stats/${config.name}.json`),
analyzerMode: 'static',
generateStatsFile: true,
openAnalyzer: false,
logLevel: 'info',
defaultSizes: 'gzip',
statsOptions: 'normal'
}, options.analyze);
return [new BundleAnalyzerPlugin(analyzerOptions)];
}
return [];
}
function createHtmlWebpackPlugin (chunks, publicPath, filename, tags) {
filename = filename + '.html';
return new HtmlWebpackPlugin({
title: chunks.join(' - '),
chunks: 'all',
template: path.resolve(__dirname, '../tmpl', 'index.html'),
filename,
templateParameters: (compilation, assets, assetTags) => {
return {
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options: {
title: assetTags.title
}
},
publicPath,
tags,
base: path.relative(`/${path.dirname(filename)}`, '/')
};
}
});
}
function createHtmlWebpackPlugins (entries, publicPath) {
return [
createHtmlWebpackPlugin(entries.map(entry => entry.name), publicPath, 'index', entries.reduce((result, entry) => {
result.push(...getTagHTMLFromEntry(entry));
return result;
}, []))
];
}
function pluginReplace (plugin, replacments) {
const keys = Object.keys(replacments);
for (let i = 0; i < keys.length; i++) {
if (plugin.constructor.name === keys[Number(i)]) {
return [].concat(replacments[String(keys[Number(i)])]).map(options => new plugin.constructor(options));
}
}
return [plugin];
}
function getJSFilesFromStats (stats) {
const name = stats.compilation.name;
const assets = stats.toJson().assetsByChunkName;
const files = Object.keys(assets).map((asset) => {
return {
asset,
file: assets[String(asset)]
};
});
return {
timestamp: stats.endTime,
hash: stats.hash,
name,
files
};
}
function normalizeConfigs (builderConfigs, webpackConfigs) {
return builderConfigs.map((buildConfig) => {
const webpackConfig = webpackConfigs.find(config => config.name === buildConfig.name);
buildConfig.entry = webpackConfig.entry;
return buildConfig;
});
}
function prepareConfigs (builderConfigs, webpackConfigs, nuxt, options) {
const configs = normalizeConfigs(builderConfigs, webpackConfigs);
const configNames = ['client'];
if (options.modern) {
configNames.push('modern');
}
return Promise.all(Object.keys(options.entry).map((entryName, i) => {
return Promise.all(configs.filter(config => configNames.includes(config.name))
.map(config => getWebpackConfig(entryName, nuxt, config, Object.assign({}, options, { entry: { [entryName]: options.entry[String(entryName)] } }))));
}));
}
function getBuilderWebpackConfigs (builder) {
const bundles = builder.bundleBuilder.compilers.map((compiler) => {
return compiler.name.substring(0, 1).toUpperCase() + compiler.name.substring(1);
});
return Promise.all(bundles.map(name => builder.bundleBuilder.getWebpackConfig(name)));
}
/**
* Property "use.options.modules.exportOnlyLocals" must be removed if static is defined as the target and "nuxt.options.extractCSS" is active.
*/
function fixCSSLoaderRulesForExtractCSS (nuxt, rules) {
if (nuxt.options.build.extractCSS) {
return rules.map((rule) => {
if (rule.oneOf) {
rule.oneOf.forEach(oneOf => oneOf.use && oneOf.use.forEach((use) => {
if (use.options && use.options.modules) {
delete use.options.modules.exportOnlyLocals;
}
}));
}
return rule;
});
}
return rules;
}
module.exports = {
build,
getWebpackConfig,
getJSFilesFromStats,
prepareConfigs,
getBuilderWebpackConfigs
};