@nuxt/webpack-builder 0.4.3 → 3.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1083 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const path = require('path');
6
- const pify = require('pify');
7
- const webpack = require('webpack');
8
- const Glob = require('glob');
9
- const webpackDevMiddleware = require('webpack-dev-middleware');
10
- const webpackHotMiddleware = require('webpack-hot-middleware');
11
- const consola = require('consola');
12
- const memfs = require('memfs');
13
- const querystring = require('querystring');
14
- const webpackBundleAnalyzer = require('webpack-bundle-analyzer');
15
- const lodash = require('lodash');
16
- const TimeFixPlugin = require('time-fix-plugin');
17
- const WebpackBar = require('webpackbar');
18
- const FriendlyErrorsWebpackPlugin = require('@nuxt/friendly-errors-webpack-plugin');
19
- const ufo = require('ufo');
20
- const esbuildLoader = require('esbuild-loader');
21
- const MiniCssExtractPlugin = require('mini-css-extract-plugin');
22
- const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
23
- const VueLoaderPlugin = require('vue-loader/dist/pluginWebpack5');
24
- const hash = require('hash-sum');
25
- const fsExtra = require('fs-extra');
26
-
27
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
28
-
29
- const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
30
- const pify__default = /*#__PURE__*/_interopDefaultLegacy(pify);
31
- const webpack__default = /*#__PURE__*/_interopDefaultLegacy(webpack);
32
- const Glob__default = /*#__PURE__*/_interopDefaultLegacy(Glob);
33
- const webpackDevMiddleware__default = /*#__PURE__*/_interopDefaultLegacy(webpackDevMiddleware);
34
- const webpackHotMiddleware__default = /*#__PURE__*/_interopDefaultLegacy(webpackHotMiddleware);
35
- const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
36
- const querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
37
- const TimeFixPlugin__default = /*#__PURE__*/_interopDefaultLegacy(TimeFixPlugin);
38
- const WebpackBar__default = /*#__PURE__*/_interopDefaultLegacy(WebpackBar);
39
- const FriendlyErrorsWebpackPlugin__default = /*#__PURE__*/_interopDefaultLegacy(FriendlyErrorsWebpackPlugin);
40
- const MiniCssExtractPlugin__default = /*#__PURE__*/_interopDefaultLegacy(MiniCssExtractPlugin);
41
- const CssMinimizerPlugin__default = /*#__PURE__*/_interopDefaultLegacy(CssMinimizerPlugin);
42
- const VueLoaderPlugin__default = /*#__PURE__*/_interopDefaultLegacy(VueLoaderPlugin);
43
- const hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
44
-
45
- var __defProp$7 = Object.defineProperty;
46
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
47
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
48
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
49
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
50
- var __spreadValues$7 = (a, b) => {
51
- for (var prop in b || (b = {}))
52
- if (__hasOwnProp$7.call(b, prop))
53
- __defNormalProp$7(a, prop, b[prop]);
54
- if (__getOwnPropSymbols$7)
55
- for (var prop of __getOwnPropSymbols$7(b)) {
56
- if (__propIsEnum$7.call(b, prop))
57
- __defNormalProp$7(a, prop, b[prop]);
58
- }
59
- return a;
60
- };
61
- function createMFS() {
62
- const fs = memfs.createFsFromVolume(new memfs.Volume());
63
- const _fs = __spreadValues$7({}, fs);
64
- _fs.join = path__default.join;
65
- _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
66
- _fs.readFile = pify__default(_fs.readFile);
67
- return _fs;
68
- }
69
-
70
- var __defProp$6 = Object.defineProperty;
71
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
72
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
73
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
74
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
75
- var __spreadValues$6 = (a, b) => {
76
- for (var prop in b || (b = {}))
77
- if (__hasOwnProp$6.call(b, prop))
78
- __defNormalProp$6(a, prop, b[prop]);
79
- if (__getOwnPropSymbols$6)
80
- for (var prop of __getOwnPropSymbols$6(b)) {
81
- if (__propIsEnum$6.call(b, prop))
82
- __defNormalProp$6(a, prop, b[prop]);
83
- }
84
- return a;
85
- };
86
- function createWebpackConfigContext({ nuxt }) {
87
- return {
88
- nuxt,
89
- options: nuxt.options,
90
- config: {},
91
- name: "base",
92
- isDev: nuxt.options.dev,
93
- isServer: false,
94
- isClient: false,
95
- isModern: void 0,
96
- isLegacy: false,
97
- alias: {},
98
- transpile: []
99
- };
100
- }
101
- function applyPresets(ctx, presets) {
102
- if (!Array.isArray(presets)) {
103
- presets = [presets];
104
- }
105
- for (const preset of presets) {
106
- if (Array.isArray(preset)) {
107
- preset[0](ctx, preset[1]);
108
- } else {
109
- preset(ctx);
110
- }
111
- }
112
- }
113
- function fileName(ctx, key) {
114
- const { options } = ctx;
115
- let fileName2 = options.build.filenames[key];
116
- if (typeof fileName2 === "function") {
117
- fileName2 = fileName2(ctx);
118
- }
119
- if (typeof fileName2 === "string" && options.dev) {
120
- const hash = /\[(chunkhash|contenthash|hash)(?::(\d+))?]/.exec(fileName2);
121
- if (hash) {
122
- consola__default.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
123
- }
124
- }
125
- return fileName2;
126
- }
127
- function getWebpackConfig(ctx) {
128
- const { options, config } = ctx;
129
- const builder = {};
130
- const loaders = [];
131
- const { extend } = options.build;
132
- if (typeof extend === "function") {
133
- const extendedConfig = extend.call(builder, config, __spreadValues$6({ loaders }, ctx)) || config;
134
- const pragma = /@|#/;
135
- const { devtool } = extendedConfig;
136
- if (typeof devtool === "string" && pragma.test(devtool)) {
137
- extendedConfig.devtool = devtool.replace(pragma, "");
138
- consola__default.warn(`devtool has been normalized to ${extendedConfig.devtool} as webpack documented value`);
139
- }
140
- return extendedConfig;
141
- }
142
- return lodash.cloneDeep(config);
143
- }
144
-
145
- var __defProp$5 = Object.defineProperty;
146
- var __defProps$3 = Object.defineProperties;
147
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
148
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
149
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
150
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
151
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
152
- var __spreadValues$5 = (a, b) => {
153
- for (var prop in b || (b = {}))
154
- if (__hasOwnProp$5.call(b, prop))
155
- __defNormalProp$5(a, prop, b[prop]);
156
- if (__getOwnPropSymbols$5)
157
- for (var prop of __getOwnPropSymbols$5(b)) {
158
- if (__propIsEnum$5.call(b, prop))
159
- __defNormalProp$5(a, prop, b[prop]);
160
- }
161
- return a;
162
- };
163
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
164
- function assets(ctx) {
165
- const { options } = ctx;
166
- ctx.config.module.rules.push({
167
- test: /\.(png|jpe?g|gif|svg|webp)$/i,
168
- use: [{
169
- loader: "url-loader",
170
- options: __spreadProps$3(__spreadValues$5({}, options.build.loaders.imgUrl), {
171
- name: fileName(ctx, "img")
172
- })
173
- }]
174
- }, {
175
- test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
176
- use: [{
177
- loader: "url-loader",
178
- options: __spreadProps$3(__spreadValues$5({}, options.build.loaders.fontUrl), {
179
- name: fileName(ctx, "font")
180
- })
181
- }]
182
- }, {
183
- test: /\.(webm|mp4|ogv)$/i,
184
- use: [{
185
- loader: "file-loader",
186
- options: __spreadProps$3(__spreadValues$5({}, options.build.loaders.file), {
187
- name: fileName(ctx, "video")
188
- })
189
- }]
190
- });
191
- }
192
-
193
- class WarningIgnorePlugin {
194
- constructor(filter) {
195
- this.filter = filter;
196
- }
197
- apply(compiler) {
198
- compiler.hooks.done.tap("warnfix-plugin", (stats) => {
199
- stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
200
- });
201
- }
202
- }
203
-
204
- var __defProp$4 = Object.defineProperty;
205
- var __defProps$2 = Object.defineProperties;
206
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
207
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
208
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
209
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
210
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
211
- var __spreadValues$4 = (a, b) => {
212
- for (var prop in b || (b = {}))
213
- if (__hasOwnProp$4.call(b, prop))
214
- __defNormalProp$4(a, prop, b[prop]);
215
- if (__getOwnPropSymbols$4)
216
- for (var prop of __getOwnPropSymbols$4(b)) {
217
- if (__propIsEnum$4.call(b, prop))
218
- __defNormalProp$4(a, prop, b[prop]);
219
- }
220
- return a;
221
- };
222
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
223
- function base(ctx) {
224
- applyPresets(ctx, [
225
- baseAlias,
226
- baseConfig,
227
- basePlugins,
228
- baseResolve
229
- ]);
230
- }
231
- function baseConfig(ctx) {
232
- const { options } = ctx;
233
- ctx.config = __spreadValues$4({
234
- name: ctx.name,
235
- entry: { app: [path.resolve(options.buildDir, "entry")] },
236
- module: { rules: [] },
237
- plugins: [],
238
- externals: [],
239
- optimization: __spreadProps$2(__spreadValues$4({}, options.build.optimization), {
240
- minimizer: []
241
- }),
242
- mode: ctx.isDev ? "development" : "production",
243
- cache: getCache(ctx),
244
- output: getOutput(ctx),
245
- stats: "none"
246
- }, ctx.config);
247
- }
248
- function basePlugins(ctx) {
249
- const { config, options, nuxt } = ctx;
250
- if (options.dev) {
251
- config.plugins.push(new TimeFixPlugin__default());
252
- }
253
- config.plugins.push(...options.build.plugins || []);
254
- config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
255
- config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
256
- if (ctx.isServer || ctx.isDev && !options.build.quiet && options.build.friendlyErrors) {
257
- ctx.config.plugins.push(new FriendlyErrorsWebpackPlugin__default({
258
- clearConsole: false,
259
- reporter: "consola",
260
- logLevel: "ERROR"
261
- }));
262
- }
263
- const colors = {
264
- client: "green",
265
- server: "orange",
266
- modern: "blue"
267
- };
268
- config.plugins.push(new WebpackBar__default({
269
- name: ctx.name,
270
- color: colors[ctx.name],
271
- reporters: ["stats"],
272
- stats: !ctx.isDev,
273
- reporter: {
274
- change: (_, { shortPath }) => {
275
- if (!ctx.isServer) {
276
- nuxt.callHook("bundler:change", shortPath);
277
- }
278
- },
279
- done: ({ state }) => {
280
- if (state.hasErrors) {
281
- nuxt.callHook("bundler:error");
282
- } else {
283
- consola__default.success(`${state.name} ${state.message}`);
284
- }
285
- },
286
- allDone: () => {
287
- nuxt.callHook("bundler:done");
288
- },
289
- progress({ statesArray }) {
290
- nuxt.callHook("bundler:progress", statesArray);
291
- }
292
- }
293
- }));
294
- }
295
- function baseAlias(ctx) {
296
- const { options } = ctx;
297
- ctx.alias = __spreadValues$4(__spreadValues$4({
298
- "#app": options.appDir,
299
- "#build": options.buildDir
300
- }, options.alias), ctx.alias);
301
- }
302
- function baseResolve(ctx) {
303
- const { options, config } = ctx;
304
- const webpackModulesDir = ["node_modules"].concat(options.modulesDir);
305
- config.resolve = __spreadValues$4({
306
- extensions: [".wasm", ".mjs", ".js", ".ts", ".json", ".vue", ".jsx", ".tsx"],
307
- alias: ctx.alias,
308
- modules: webpackModulesDir,
309
- fullySpecified: false
310
- }, config.resolve);
311
- config.resolveLoader = __spreadValues$4({
312
- modules: webpackModulesDir
313
- }, config.resolveLoader);
314
- }
315
- function getCache(ctx) {
316
- const { options } = ctx;
317
- if (!options.dev) {
318
- return false;
319
- }
320
- }
321
- function getOutput(ctx) {
322
- const { options } = ctx;
323
- return {
324
- path: path.resolve(options.buildDir, "dist", ctx.isServer ? "server" : "client"),
325
- filename: fileName(ctx, "app"),
326
- chunkFilename: fileName(ctx, "chunk"),
327
- publicPath: ufo.hasProtocol(options.build.publicPath, true) ? options.build.publicPath : ufo.joinURL(options.router.base, options.build.publicPath)
328
- };
329
- }
330
- function getWarningIgnoreFilter(ctx) {
331
- const { options } = ctx;
332
- const filters = [
333
- (warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"),
334
- ...options.build.warningIgnoreFilters || []
335
- ];
336
- return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
337
- }
338
- function getEnv(ctx) {
339
- const { options } = ctx;
340
- const _env = {
341
- "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
342
- "process.mode": JSON.stringify(ctx.config.mode),
343
- "process.dev": options.dev,
344
- "process.static": options.target === "static",
345
- "process.target": JSON.stringify(options.target),
346
- "process.env.VUE_ENV": JSON.stringify(ctx.name),
347
- "process.browser": ctx.isClient,
348
- "process.client": ctx.isClient,
349
- "process.server": ctx.isServer,
350
- "process.modern": ctx.isModern
351
- };
352
- if (options.build.aggressiveCodeRemoval) {
353
- _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
354
- _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
355
- }
356
- Object.entries(options.env).forEach(([key, value]) => {
357
- const isNative = ["boolean", "number"].includes(typeof value);
358
- _env["process.env." + key] = isNative ? value : JSON.stringify(value);
359
- });
360
- return _env;
361
- }
362
-
363
- function esbuild(ctx) {
364
- const { config } = ctx;
365
- const target = ctx.isServer ? "node14" : "chrome85";
366
- config.optimization.minimizer.push(new esbuildLoader.ESBuildMinifyPlugin());
367
- config.module.rules.push({
368
- test: /\.m?[jt]sx?$/i,
369
- loader: "esbuild-loader",
370
- exclude: (file) => {
371
- file = file.split("node_modules", 2)[1];
372
- if (!file) {
373
- return false;
374
- }
375
- return !ctx.transpile.some((module) => module.test(file));
376
- },
377
- resolve: {
378
- fullySpecified: false
379
- },
380
- options: {
381
- loader: "ts",
382
- target
383
- }
384
- }, {
385
- test: /\.tsx$/,
386
- loader: "esbuild-loader",
387
- options: {
388
- loader: "tsx",
389
- target
390
- }
391
- });
392
- }
393
-
394
- function pug(ctx) {
395
- ctx.config.module.rules.push({
396
- test: /\.pug$/i,
397
- oneOf: [
398
- {
399
- resourceQuery: /^\?vue/i,
400
- use: [{
401
- loader: "pug-plain-loader",
402
- options: ctx.options.build.loaders.pugPlain
403
- }]
404
- },
405
- {
406
- use: [
407
- "raw-loader",
408
- {
409
- loader: "pug-plain-loader",
410
- options: ctx.options.build.loaders.pugPlain
411
- }
412
- ]
413
- }
414
- ]
415
- });
416
- }
417
-
418
- var __defProp$3 = Object.defineProperty;
419
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
420
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
421
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
422
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
423
- var __spreadValues$3 = (a, b) => {
424
- for (var prop in b || (b = {}))
425
- if (__hasOwnProp$3.call(b, prop))
426
- __defNormalProp$3(a, prop, b[prop]);
427
- if (__getOwnPropSymbols$3)
428
- for (var prop of __getOwnPropSymbols$3(b)) {
429
- if (__propIsEnum$3.call(b, prop))
430
- __defNormalProp$3(a, prop, b[prop]);
431
- }
432
- return a;
433
- };
434
- function style(ctx) {
435
- applyPresets(ctx, [
436
- loaders,
437
- extractCSS,
438
- minimizer
439
- ]);
440
- }
441
- function minimizer(ctx) {
442
- const { options, config } = ctx;
443
- if (options.build.optimizeCSS && Array.isArray(config.optimization.minimizer)) {
444
- config.optimization.minimizer.push(new CssMinimizerPlugin__default(__spreadValues$3({}, options.build.optimizeCSS)));
445
- }
446
- }
447
- function extractCSS(ctx) {
448
- const { options, config } = ctx;
449
- if (options.build.extractCSS) {
450
- config.plugins.push(new MiniCssExtractPlugin__default(__spreadValues$3({
451
- filename: fileName(ctx, "css"),
452
- chunkFilename: fileName(ctx, "css")
453
- }, options.build.extractCSS)));
454
- }
455
- }
456
- function loaders(ctx) {
457
- const { config, options } = ctx;
458
- config.module.rules.push(createdStyleRule("css", /\.css$/i, null, ctx));
459
- config.module.rules.push(createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
460
- const lessLoader = { loader: "less-loader", options: options.build.loaders.less };
461
- config.module.rules.push(createdStyleRule("less", /\.less$/i, lessLoader, ctx));
462
- const sassLoader = { loader: "sass-loader", options: options.build.loaders.sass };
463
- config.module.rules.push(createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
464
- const scssLoader = { loader: "sass-loader", options: options.build.loaders.scss };
465
- config.module.rules.push(createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
466
- const stylusLoader = { loader: "stylus-loader", options: options.build.loaders.stylus };
467
- config.module.rules.push(createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
468
- }
469
- function createdStyleRule(lang, test, processorLoader, ctx) {
470
- const { options } = ctx;
471
- const styleLoaders = [
472
- processorLoader,
473
- createStyleResourcesLoaderRule(lang, options.build.styleResources, options.rootDir)
474
- ].filter(Boolean);
475
- options.build.loaders.css.importLoaders = options.build.loaders.cssModules.importLoaders = styleLoaders.length;
476
- const cssLoaders = createCssLoadersRule(ctx, options.build.loaders.css);
477
- const cssModuleLoaders = createCssLoadersRule(ctx, options.build.loaders.cssModules);
478
- return {
479
- test,
480
- oneOf: [
481
- {
482
- resourceQuery: /module/,
483
- use: cssModuleLoaders.concat(styleLoaders)
484
- },
485
- {
486
- use: cssLoaders.concat(styleLoaders)
487
- }
488
- ]
489
- };
490
- }
491
- function createCssLoadersRule(ctx, cssLoaderOptions) {
492
- const { options } = ctx;
493
- const cssLoader = { loader: "css-loader", options: cssLoaderOptions };
494
- if (options.build.extractCSS) {
495
- if (ctx.isServer) {
496
- return [cssLoader];
497
- }
498
- return [
499
- {
500
- loader: MiniCssExtractPlugin__default.loader,
501
- options: { reloadAll: ctx.isDev, hot: ctx.isDev }
502
- },
503
- cssLoader
504
- ];
505
- }
506
- return [
507
- {
508
- loader: "vue-style-loader",
509
- options: options.build.loaders.vueStyle
510
- },
511
- cssLoader
512
- ];
513
- }
514
- function createStyleResourcesLoaderRule(styleLang, styleResources, rootDir) {
515
- if (!styleResources[styleLang]) {
516
- return;
517
- }
518
- return {
519
- loader: "style-resources-loader",
520
- options: __spreadValues$3({
521
- patterns: Array.from(styleResources[styleLang]).map((p) => path__default.resolve(rootDir, p))
522
- }, styleResources.options)
523
- };
524
- }
525
-
526
- const validate = (compiler) => {
527
- if (compiler.options.target !== "node") {
528
- consola__default.warn('webpack config `target` should be "node".');
529
- }
530
- const libraryType = compiler.options.output.library.type;
531
- if (libraryType !== "commonjs2") {
532
- consola__default.warn('webpack config `output.libraryTarget` should be "commonjs2".');
533
- }
534
- if (!compiler.options.externals) {
535
- consola__default.info("It is recommended to externalize dependencies in the server build for better build performance.");
536
- }
537
- };
538
- const isJSRegExp = /\.js(\?[^.]+)?$/;
539
- const isJS = (file) => isJSRegExp.test(file);
540
- const extractQueryPartJS = (file) => isJSRegExp.exec(file)[1];
541
- const isCSS = (file) => /\.css(\?[^.]+)?$/.test(file);
542
- const isHotUpdate = (file) => file.includes("hot-update");
543
-
544
- class VueSSRClientPlugin {
545
- constructor(options = {}) {
546
- this.options = Object.assign({
547
- filename: null
548
- }, options);
549
- }
550
- apply(compiler) {
551
- compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
552
- const stats = compilation.getStats().toJson();
553
- const allFiles = lodash.uniq(stats.assets.map((a) => a.name)).filter((file) => !isHotUpdate(file));
554
- const initialFiles = lodash.uniq(Object.keys(stats.entrypoints).map((name) => stats.entrypoints[name].assets).reduce((files, entryAssets) => files.concat(entryAssets.map((entryAsset) => entryAsset.name)), []).filter((file) => isJS(file) || isCSS(file))).filter((file) => !isHotUpdate(file));
555
- const asyncFiles = allFiles.filter((file) => isJS(file) || isCSS(file)).filter((file) => !initialFiles.includes(file)).filter((file) => !isHotUpdate(file));
556
- const assetsMapping = {};
557
- stats.assets.filter(({ name }) => isJS(name)).filter(({ name }) => !isHotUpdate(name)).forEach(({ name, chunkNames }) => {
558
- const componentHash = hash__default(chunkNames.join("|"));
559
- if (!assetsMapping[componentHash]) {
560
- assetsMapping[componentHash] = [];
561
- }
562
- assetsMapping[componentHash].push(name);
563
- });
564
- const manifest = {
565
- publicPath: stats.publicPath,
566
- all: allFiles,
567
- initial: initialFiles,
568
- async: asyncFiles,
569
- modules: {},
570
- assetsMapping
571
- };
572
- const { entrypoints, namedChunkGroups } = stats;
573
- const assetModules = stats.modules.filter((m) => m.assets.length);
574
- const fileToIndex = (file) => manifest.all.indexOf(file);
575
- stats.modules.forEach((m) => {
576
- if (m.chunks.length === 1) {
577
- const [cid] = m.chunks;
578
- const chunk = stats.chunks.find((c) => c.id === cid);
579
- if (!chunk || !chunk.files) {
580
- return;
581
- }
582
- const id = m.identifier.replace(/\s\w+$/, "");
583
- const filesSet = new Set(chunk.files.map(fileToIndex).filter((i) => i !== -1));
584
- for (const chunkName of chunk.names) {
585
- if (!entrypoints[chunkName]) {
586
- const chunkGroup = namedChunkGroups[chunkName];
587
- if (chunkGroup) {
588
- for (const asset of chunkGroup.assets) {
589
- filesSet.add(fileToIndex(asset.name));
590
- }
591
- }
592
- }
593
- }
594
- const files = Array.from(filesSet);
595
- manifest.modules[hash__default(id)] = files;
596
- if (Array.isArray(m.modules)) {
597
- for (const concatenatedModule of m.modules) {
598
- const id2 = hash__default(concatenatedModule.identifier.replace(/\s\w+$/, ""));
599
- if (!manifest.modules[id2]) {
600
- manifest.modules[id2] = files;
601
- }
602
- }
603
- }
604
- assetModules.forEach((m2) => {
605
- if (m2.chunks.includes(cid)) {
606
- files.push.apply(files, m2.assets.map(fileToIndex));
607
- }
608
- });
609
- }
610
- });
611
- const src = JSON.stringify(manifest, null, 2);
612
- await fsExtra.mkdirp(path.dirname(this.options.filename));
613
- await fsExtra.writeFile(this.options.filename, src);
614
- });
615
- }
616
- }
617
-
618
- class VueSSRServerPlugin {
619
- constructor(options = {}) {
620
- this.options = Object.assign({
621
- filename: null
622
- }, options);
623
- }
624
- apply(compiler) {
625
- validate(compiler);
626
- compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
627
- compilation.hooks.processAssets.tapAsync({
628
- name: "VueSSRServerPlugin",
629
- stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
630
- }, (assets, cb) => {
631
- const stats = compilation.getStats().toJson();
632
- const [entryName] = Object.keys(stats.entrypoints);
633
- const entryInfo = stats.entrypoints[entryName];
634
- if (!entryInfo) {
635
- return cb();
636
- }
637
- const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
638
- if (entryAssets.length > 1) {
639
- throw new Error("Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config.");
640
- }
641
- const [entry] = entryAssets;
642
- if (!entry || typeof entry.name !== "string") {
643
- throw new Error(`Entry "${entryName}" not found. Did you specify the correct entry option?`);
644
- }
645
- const bundle = {
646
- entry: entry.name,
647
- files: {},
648
- maps: {}
649
- };
650
- stats.assets.forEach((asset) => {
651
- if (isJS(asset.name)) {
652
- const queryPart = extractQueryPartJS(asset.name);
653
- if (queryPart !== void 0) {
654
- bundle.files[asset.name] = asset.name.replace(queryPart, "");
655
- } else {
656
- bundle.files[asset.name] = asset.name;
657
- }
658
- } else if (asset.name.match(/\.js\.map$/)) {
659
- bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
660
- } else {
661
- delete assets[asset.name];
662
- }
663
- });
664
- const src = JSON.stringify(bundle, null, 2);
665
- assets[this.options.filename] = {
666
- source: () => src,
667
- size: () => src.length
668
- };
669
- cb();
670
- });
671
- });
672
- }
673
- }
674
-
675
- function vue(ctx) {
676
- const { options, config } = ctx;
677
- config.plugins.push(new VueLoaderPlugin__default());
678
- config.module.rules.push({
679
- test: /\.vue$/i,
680
- loader: "vue-loader",
681
- options: options.build.loaders.vue
682
- });
683
- if (ctx.isClient) {
684
- config.plugins.push(new VueSSRClientPlugin({
685
- filename: path.resolve(options.buildDir, "dist/server", `${ctx.name}.manifest.json`)
686
- }));
687
- } else {
688
- config.plugins.push(new VueSSRServerPlugin({
689
- filename: `${ctx.name}.manifest.json`
690
- }));
691
- }
692
- config.plugins.push(new webpack.DefinePlugin({
693
- __VUE_OPTIONS_API__: "true",
694
- __VUE_PROD_DEVTOOLS__: "false"
695
- }));
696
- }
697
-
698
- function nuxt(ctx) {
699
- applyPresets(ctx, [
700
- base,
701
- assets,
702
- esbuild,
703
- pug,
704
- style,
705
- vue
706
- ]);
707
- }
708
-
709
- var __defProp$2 = Object.defineProperty;
710
- var __defProps$1 = Object.defineProperties;
711
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
712
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
713
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
714
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
715
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
716
- var __spreadValues$2 = (a, b) => {
717
- for (var prop in b || (b = {}))
718
- if (__hasOwnProp$2.call(b, prop))
719
- __defNormalProp$2(a, prop, b[prop]);
720
- if (__getOwnPropSymbols$2)
721
- for (var prop of __getOwnPropSymbols$2(b)) {
722
- if (__propIsEnum$2.call(b, prop))
723
- __defNormalProp$2(a, prop, b[prop]);
724
- }
725
- return a;
726
- };
727
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
728
- function client(ctx) {
729
- ctx.name = "client";
730
- ctx.isClient = true;
731
- applyPresets(ctx, [
732
- nuxt,
733
- clientPlugins,
734
- clientOptimization,
735
- clientDevtool,
736
- clientPerformance,
737
- clientHMR
738
- ]);
739
- }
740
- function clientDevtool(ctx) {
741
- if (!ctx.isDev) {
742
- ctx.config.devtool = false;
743
- return;
744
- }
745
- const scriptPolicy = getCspScriptPolicy(ctx);
746
- const noUnsafeEval = scriptPolicy && !scriptPolicy.includes("'unsafe-eval'");
747
- ctx.config.devtool = noUnsafeEval ? "cheap-module-source-map" : "eval-cheap-module-source-map";
748
- }
749
- function clientPerformance(ctx) {
750
- ctx.config.performance = __spreadValues$2({
751
- maxEntrypointSize: 1e3 * 1024,
752
- hints: ctx.isDev ? false : "warning"
753
- }, ctx.config.performance);
754
- }
755
- function clientHMR(ctx) {
756
- var _a;
757
- const { options, config } = ctx;
758
- if (!ctx.isDev) {
759
- return;
760
- }
761
- const clientOptions = ((_a = options.build.hotMiddleware) == null ? void 0 : _a.client) || {};
762
- const hotMiddlewareClientOptions = __spreadProps$1(__spreadValues$2({
763
- reload: true,
764
- timeout: 3e4,
765
- path: `${options.router.base}/__webpack_hmr/${ctx.name}`.replace(/\/\//g, "/")
766
- }, clientOptions), {
767
- ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
768
- overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
769
- name: ctx.name
770
- });
771
- const hotMiddlewareClientOptionsStr = querystring__default.stringify(hotMiddlewareClientOptions);
772
- const app = config.entry.app;
773
- app.unshift(`webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`);
774
- config.plugins.push(new webpack__default.HotModuleReplacementPlugin());
775
- }
776
- function clientOptimization(ctx) {
777
- const { options, config } = ctx;
778
- config.optimization = __spreadValues$2(__spreadValues$2({}, config.optimization), options.build.optimization);
779
- }
780
- function clientPlugins(ctx) {
781
- const { options, config } = ctx;
782
- if (!ctx.isDev && options.build.analyze) {
783
- const statsDir = path__default.resolve(options.buildDir, "stats");
784
- config.plugins.push(new webpackBundleAnalyzer.BundleAnalyzerPlugin(__spreadValues$2({
785
- analyzerMode: "static",
786
- defaultSizes: "gzip",
787
- generateStatsFile: true,
788
- openAnalyzer: !options.build.quiet,
789
- reportFilename: path__default.resolve(statsDir, `${ctx.name}.html`),
790
- statsFilename: path__default.resolve(statsDir, `${ctx.name}.json`)
791
- }, options.build.analyze)));
792
- }
793
- }
794
- function getCspScriptPolicy(ctx) {
795
- const { csp } = ctx.options.render;
796
- if (typeof csp === "object") {
797
- const { policies = {} } = csp;
798
- return policies["script-src"] || policies["default-src"] || [];
799
- }
800
- }
801
-
802
- var __defProp$1 = Object.defineProperty;
803
- var __defProps = Object.defineProperties;
804
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
805
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
806
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
807
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
808
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
809
- var __spreadValues$1 = (a, b) => {
810
- for (var prop in b || (b = {}))
811
- if (__hasOwnProp$1.call(b, prop))
812
- __defNormalProp$1(a, prop, b[prop]);
813
- if (__getOwnPropSymbols$1)
814
- for (var prop of __getOwnPropSymbols$1(b)) {
815
- if (__propIsEnum$1.call(b, prop))
816
- __defNormalProp$1(a, prop, b[prop]);
817
- }
818
- return a;
819
- };
820
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
821
- function node(ctx) {
822
- const { config } = ctx;
823
- config.target = "node";
824
- config.node = false;
825
- config.resolve.mainFields = ["main", "module"];
826
- config.output = __spreadProps(__spreadValues$1({}, config.output), {
827
- chunkFilename: "[name].js",
828
- libraryTarget: "commonjs2"
829
- });
830
- config.performance = __spreadProps(__spreadValues$1({}, config.performance), {
831
- hints: false,
832
- maxEntrypointSize: Infinity,
833
- maxAssetSize: Infinity
834
- });
835
- }
836
-
837
- function server(ctx) {
838
- ctx.name = "server";
839
- ctx.isServer = true;
840
- applyPresets(ctx, [
841
- nuxt,
842
- node,
843
- serverStandalone,
844
- serverPreset,
845
- serverPlugins
846
- ]);
847
- return getWebpackConfig(ctx);
848
- }
849
- function serverPreset(ctx) {
850
- const { config } = ctx;
851
- config.output.filename = "server.js";
852
- config.devtool = "cheap-module-source-map";
853
- config.optimization = {
854
- splitChunks: false,
855
- minimize: false
856
- };
857
- }
858
- function serverStandalone(ctx) {
859
- const inline = [
860
- "src/",
861
- "@nuxt/app",
862
- "vuex5",
863
- "!",
864
- "-!",
865
- "~",
866
- "@/",
867
- "#",
868
- ...ctx.options.build.transpile
869
- ];
870
- if (!Array.isArray(ctx.config.externals)) {
871
- return;
872
- }
873
- ctx.config.externals.push(({ request }, cb) => {
874
- if (request[0] === "." || request[0] === "/" || inline.find((prefix) => request.startsWith(prefix))) {
875
- return cb(null, false);
876
- }
877
- return cb(null, true);
878
- });
879
- }
880
- function serverPlugins(ctx) {
881
- const { config, options } = ctx;
882
- if (options.build.serverURLPolyfill) {
883
- config.plugins.push(new webpack.ProvidePlugin({
884
- URL: [options.build.serverURLPolyfill, "URL"],
885
- URLSearchParams: [options.build.serverURLPolyfill, "URLSearchParams"]
886
- }));
887
- }
888
- }
889
-
890
- var __defProp = Object.defineProperty;
891
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
892
- var __hasOwnProp = Object.prototype.hasOwnProperty;
893
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
894
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
895
- var __spreadValues = (a, b) => {
896
- for (var prop in b || (b = {}))
897
- if (__hasOwnProp.call(b, prop))
898
- __defNormalProp(a, prop, b[prop]);
899
- if (__getOwnPropSymbols)
900
- for (var prop of __getOwnPropSymbols(b)) {
901
- if (__propIsEnum.call(b, prop))
902
- __defNormalProp(a, prop, b[prop]);
903
- }
904
- return a;
905
- };
906
- var __objRest = (source, exclude) => {
907
- var target = {};
908
- for (var prop in source)
909
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
910
- target[prop] = source[prop];
911
- if (source != null && __getOwnPropSymbols)
912
- for (var prop of __getOwnPropSymbols(source)) {
913
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
914
- target[prop] = source[prop];
915
- }
916
- return target;
917
- };
918
- const glob = pify__default(Glob__default);
919
- class WebpackBundler {
920
- constructor(nuxt) {
921
- this.nuxt = nuxt;
922
- this.plugins = [];
923
- this.compilers = [];
924
- this.compilersWatching = [];
925
- this.devMiddleware = {};
926
- this.hotMiddleware = {};
927
- this.middleware = this.middleware.bind(this);
928
- if (this.nuxt.options.dev) {
929
- this.mfs = createMFS();
930
- }
931
- }
932
- getWebpackConfig(name) {
933
- const ctx = createWebpackConfigContext({ nuxt: this.nuxt });
934
- if (name === "client") {
935
- applyPresets(ctx, client);
936
- } else if (name === "server") {
937
- applyPresets(ctx, server);
938
- } else {
939
- throw new Error(`Unsupported webpack config ${name}`);
940
- }
941
- return getWebpackConfig(ctx);
942
- }
943
- async build() {
944
- const { options } = this.nuxt;
945
- const webpackConfigs = [
946
- this.getWebpackConfig("client")
947
- ];
948
- webpackConfigs.push(this.getWebpackConfig("server"));
949
- await this.nuxt.callHook("webpack:config", webpackConfigs);
950
- const { styleResources } = this.nuxt.options.build;
951
- if (styleResources && Object.keys(styleResources).length) {
952
- consola__default.warn("Using styleResources without the @nuxtjs/style-resources is not suggested and can lead to severe performance issues.", "Please use https://github.com/nuxt-community/style-resources-module");
953
- for (const ext of Object.keys(styleResources)) {
954
- await Promise.all(Array.from(styleResources[ext]).map(async (p) => {
955
- const styleResourceFiles = await glob(path__default.resolve(this.nuxt.options.rootDir, p));
956
- if (!styleResourceFiles || styleResourceFiles.length === 0) {
957
- throw new Error(`Style Resource not found: ${p}`);
958
- }
959
- }));
960
- }
961
- }
962
- this.compilers = webpackConfigs.map((config) => {
963
- const compiler = webpack__default(config);
964
- if (options.dev) {
965
- compiler.outputFileSystem = this.mfs;
966
- }
967
- return compiler;
968
- });
969
- if (options.dev) {
970
- return Promise.all(this.compilers.map((c) => this.webpackCompile(c)));
971
- } else {
972
- for (const c of this.compilers) {
973
- await this.webpackCompile(c);
974
- }
975
- }
976
- }
977
- async webpackCompile(compiler) {
978
- const { name } = compiler.options;
979
- const { options } = this.nuxt;
980
- await this.nuxt.callHook("build:compile", { name, compiler });
981
- compiler.hooks.done.tap("load-resources", async (stats2) => {
982
- await this.nuxt.callHook("build:compiled", {
983
- name,
984
- compiler,
985
- stats: stats2
986
- });
987
- await this.nuxt.callHook("build:resources", this.mfs);
988
- });
989
- if (options.dev) {
990
- if (["client", "modern"].includes(name)) {
991
- return new Promise((resolve, reject) => {
992
- compiler.hooks.done.tap("nuxt-dev", () => {
993
- resolve(null);
994
- });
995
- compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
996
- reject(err);
997
- });
998
- this.webpackDev(compiler);
999
- });
1000
- }
1001
- return new Promise((resolve, reject) => {
1002
- const watching = compiler.watch(options.watchers.webpack, (err) => {
1003
- if (err) {
1004
- return reject(err);
1005
- }
1006
- resolve(null);
1007
- });
1008
- watching.closeAsync = pify__default(watching.close);
1009
- this.compilersWatching.push(watching);
1010
- });
1011
- }
1012
- compiler.run = pify__default(compiler.run);
1013
- const stats = await compiler.run();
1014
- if (stats.hasErrors()) {
1015
- const error = new Error("Nuxt build error");
1016
- if (options.build.quiet === true) {
1017
- error.stack = stats.toString("errors-only");
1018
- }
1019
- throw error;
1020
- }
1021
- await this.nuxt.callHook("build:resources");
1022
- }
1023
- async webpackDev(compiler) {
1024
- consola__default.debug("Creating webpack middleware...");
1025
- const { name } = compiler.options;
1026
- const buildOptions = this.nuxt.options.build;
1027
- const _a = buildOptions.hotMiddleware || {}, hotMiddlewareOptions = __objRest(_a, ["client"]);
1028
- this.devMiddleware[name] = pify__default(webpackDevMiddleware__default(compiler, __spreadValues({
1029
- publicPath: buildOptions.publicPath,
1030
- outputFileSystem: this.mfs,
1031
- stats: "none"
1032
- }, buildOptions.devMiddleware)));
1033
- this.devMiddleware[name].close = pify__default(this.devMiddleware[name].close);
1034
- this.compilersWatching.push(this.devMiddleware[name].context.watching);
1035
- this.hotMiddleware[name] = pify__default(webpackHotMiddleware__default(compiler, __spreadValues({
1036
- log: false,
1037
- heartbeat: 1e4,
1038
- path: `/__webpack_hmr/${name}`
1039
- }, hotMiddlewareOptions)));
1040
- await this.nuxt.callHook("server:devMiddleware", this.middleware);
1041
- }
1042
- async middleware(req, res, next) {
1043
- if (this.devMiddleware && this.devMiddleware.client) {
1044
- await this.devMiddleware.client(req, res);
1045
- }
1046
- if (this.hotMiddleware && this.hotMiddleware.client) {
1047
- await this.hotMiddleware.client(req, res);
1048
- }
1049
- next();
1050
- }
1051
- async unwatch() {
1052
- await Promise.all(this.compilersWatching.map((watching) => watching.closeAsync()));
1053
- }
1054
- async close() {
1055
- if (this.__closed) {
1056
- return;
1057
- }
1058
- this.__closed = true;
1059
- await this.unwatch();
1060
- for (const devMiddleware of Object.values(this.devMiddleware)) {
1061
- await devMiddleware.close();
1062
- }
1063
- for (const compiler of this.compilers) {
1064
- await new Promise((resolve) => compiler.close(resolve));
1065
- }
1066
- if (this.mfs) {
1067
- delete this.mfs;
1068
- }
1069
- delete this.compilers;
1070
- delete this.compilersWatching;
1071
- delete this.devMiddleware;
1072
- delete this.hotMiddleware;
1073
- }
1074
- forGenerate() {
1075
- this.nuxt.options.target = "static";
1076
- }
1077
- }
1078
- function bundle(nuxt) {
1079
- const bundler = new WebpackBundler(nuxt);
1080
- return bundler.build();
1081
- }
1082
-
1083
- exports.bundle = bundle;