@nuxt/webpack-builder 4.2.2 → 4.3.1

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.mjs CHANGED
@@ -1,193 +1,500 @@
1
- import pify from 'pify';
2
- import { fromNodeMiddleware, defineEventHandler, handleCors, getRequestHeader, createError, setHeader } from 'h3';
3
- import webpackDevMiddleware from 'webpack-dev-middleware';
4
- import webpackHotMiddleware from 'webpack-hot-middleware';
5
- import { defu } from 'defu';
6
- import { joinURL } from 'ufo';
7
- import { logger, useNitro, useNuxt } from '@nuxt/kit';
8
- import { createUnplugin } from 'unplugin';
9
- import MagicString from 'magic-string';
10
- import { webpack, WebpackBarPlugin, builder, MiniCssExtractPlugin, TsCheckerPlugin } from '#builder';
11
- import { join, resolve, basename, normalize, isAbsolute } from 'pathe';
12
- import { createFsFromVolume, Volume } from 'memfs';
13
- import querystring from 'node:querystring';
14
- import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
15
- import { defineEnv } from 'unenv';
16
- import TimeFixPlugin from 'time-fix-plugin';
17
- import FriendlyErrorsWebpackPlugin from '@nuxt/friendly-errors-webpack-plugin';
18
- import escapeRegExp from 'escape-string-regexp';
19
- import { isTest } from 'std-env';
20
- import { genObjectFromRawEntries, genString } from 'knitwork';
21
- import { EsbuildPlugin } from 'esbuild-loader';
22
- import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
23
- import createResolver from 'postcss-import-resolver';
24
- import { createJiti } from 'jiti';
25
- import VueLoaderPlugin from 'vue-loader/dist/pluginWebpack5.js';
26
- import { mkdir, writeFile } from 'node:fs/promises';
27
- import { normalizeWebpackManifest, precomputeDependencies } from 'vue-bundle-renderer';
28
- import { hash } from 'ohash';
29
- import { serialize } from 'seroval';
30
-
1
+ import { createRequire } from "node:module";
2
+ import pify from "pify";
3
+ import webpackDevMiddleware from "webpack-dev-middleware";
4
+ import webpackHotMiddleware from "webpack-hot-middleware";
5
+ import { defu } from "defu";
6
+ import { joinURL, parseURL, withTrailingSlash } from "ufo";
7
+ import { directoryToURL, logger, resolveAlias, useNitro, useNuxt } from "@nuxt/kit";
8
+ import { createUnplugin } from "unplugin";
9
+ import MagicString from "magic-string";
10
+ import webpack from "webpack";
11
+ import MiniCssExtractPlugin from "mini-css-extract-plugin";
12
+ import WebpackBarPlugin from "webpackbar";
13
+ import TsCheckerPlugin from "fork-ts-checker-webpack-plugin";
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import { pathToFileURL } from "node:url";
16
+ import { basename, isAbsolute, join, normalize, relative, resolve } from "pathe";
17
+ import { genArrayFromRaw, genObjectFromRawEntries, genString } from "knitwork";
18
+ import { compileStyle, parse } from "@vue/compiler-sfc";
19
+ import { createHash } from "node:crypto";
20
+ import { Volume, createFsFromVolume } from "memfs";
21
+ import querystring from "node:querystring";
22
+ import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
23
+ import { defineEnv } from "unenv";
24
+ import TimeFixPlugin from "time-fix-plugin";
25
+ import FriendlyErrorsWebpackPlugin from "@nuxt/friendly-errors-webpack-plugin";
26
+ import escapeRegExp from "escape-string-regexp";
27
+ import { isTest } from "std-env";
28
+ import { EsbuildPlugin } from "esbuild-loader";
29
+ import CssMinimizerPlugin from "css-minimizer-webpack-plugin";
30
+ import createResolver from "postcss-import-resolver";
31
+ import { createJiti } from "jiti";
32
+ import VueLoaderPlugin from "vue-loader/dist/pluginWebpack5.js";
33
+ import { resolveModulePath } from "exsolve";
34
+ import { mkdir, writeFile } from "node:fs/promises";
35
+ import { normalizeWebpackManifest, precomputeDependencies } from "vue-bundle-renderer";
36
+ import { hash } from "ohash";
37
+ import { serialize } from "seroval";
38
+ import { parseNodeModulePath } from "mlly";
31
39
  const defaults = {
32
- globalPublicPath: "__webpack_public_path__",
33
- sourcemap: true
40
+ globalPublicPath: "__webpack_public_path__",
41
+ sourcemap: true
34
42
  };
35
43
  const ENTRY_RE = /import ["']#build\/css["'];/;
36
44
  const DynamicBasePlugin = createUnplugin((options = {}) => {
37
- options = { ...defaults, ...options };
38
- return {
39
- name: "nuxt:dynamic-base-path",
40
- enforce: "post",
41
- transform: {
42
- filter: {
43
- id: { include: /entry/ },
44
- code: { include: ENTRY_RE }
45
- },
46
- handler(code) {
47
- const s = new MagicString(code);
48
- s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';
49
- ${options.globalPublicPath} = buildAssetsURL();
50
- `);
51
- return {
52
- code: s.toString(),
53
- map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
54
- };
55
- }
56
- }
57
- };
45
+ options = {
46
+ ...defaults,
47
+ ...options
48
+ };
49
+ return {
50
+ name: "nuxt:dynamic-base-path",
51
+ enforce: "post",
52
+ transform: {
53
+ filter: {
54
+ id: { include: /entry/ },
55
+ code: { include: ENTRY_RE }
56
+ },
57
+ handler(code) {
58
+ const s = new MagicString(code);
59
+ s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';\n${options.globalPublicPath} = buildAssetsURL();\n`);
60
+ return {
61
+ code: s.toString(),
62
+ map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
63
+ };
64
+ }
65
+ }
66
+ };
58
67
  });
59
-
68
+ const builder = "webpack";
60
69
  const pluginName = "ChunkErrorPlugin";
61
- class ChunkErrorPlugin {
62
- script = `
63
- if (typeof ${webpack.RuntimeGlobals.require} !== "undefined") {
64
- var _ensureChunk = ${webpack.RuntimeGlobals.ensureChunk};
65
- ${webpack.RuntimeGlobals.ensureChunk} = function (chunkId) {
66
- return Promise.resolve(_ensureChunk(chunkId)).catch(error => {
67
- const e = new Event('nuxt:preloadError', { cancelable: true })
68
- e.payload = error
69
- window.dispatchEvent(e)
70
- throw error
70
+ var ChunkErrorPlugin = class {
71
+ apply(compiler) {
72
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
73
+ compilation.hooks.runtimeRequirementInTree.for(webpack.RuntimeGlobals.ensureChunk).tap(pluginName, (chunk) => {
74
+ compilation.addRuntimeModule(chunk, new ChunkErrorRuntimeModule());
75
+ });
76
+ });
77
+ }
78
+ };
79
+ var ChunkErrorRuntimeModule = class extends webpack.RuntimeModule {
80
+ constructor() {
81
+ super("chunk preload error handler", webpack.RuntimeModule.STAGE_ATTACH);
82
+ }
83
+ generate() {
84
+ const { ensureChunk } = webpack.RuntimeGlobals;
85
+ return `
86
+ if (typeof ${ensureChunk} !== "undefined") {
87
+ var _ensureChunk = ${ensureChunk};
88
+ ${ensureChunk} = function (chunkId) {
89
+ return Promise.resolve(_ensureChunk(chunkId)).catch(function(error) {
90
+ var e = new Event('nuxt:preloadError', { cancelable: true });
91
+ e.payload = error;
92
+ window.dispatchEvent(e);
93
+ throw error;
71
94
  });
72
95
  };
73
- };`;
74
- apply(compiler) {
75
- compiler.hooks.thisCompilation.tap(
76
- pluginName,
77
- (compilation) => compilation.mainTemplate.hooks.localVars.tap(
78
- { name: pluginName, stage: 1 },
79
- (source) => source + this.script
80
- )
81
- );
82
- }
83
96
  }
84
-
97
+ `;
98
+ }
99
+ };
100
+ const CSS_URL_RE = /url\((['"]?)(\/[^)]+?)\1\)/g;
101
+ const isVueFile = (id) => /\.vue(?:\?|$)/.test(id);
102
+ const isCSSLike = (name) => /\.(?:css|scss|sass|less|styl(?:us)?|postcss|pcss)(?:\?|$)/.test(name);
103
+ function normalizePath(nuxt, id) {
104
+ if (!id) return null;
105
+ const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href));
106
+ const rel = relative(nuxt.options.srcDir, pathname);
107
+ if (rel.startsWith("..")) return null;
108
+ return rel;
109
+ }
110
+ function resolveFilePath(id) {
111
+ if (!id) return null;
112
+ return parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname || null;
113
+ }
114
+ function sanitizeStyleAssetName(rel) {
115
+ return rel.replace(/[\\/]/g, "_").replace(/\.{2,}/g, "_");
116
+ }
117
+ function normalizeCSSContent(css) {
118
+ return css.trim().replace(/(--[^:]+):\s*'([^']*)'/g, "$1:\"$2\"").replace(/:\s+/g, ":").replace(/\s*\{\s*/g, "{").replace(/;\s*\}/g, "}").replace(/\s*\}\s*/g, "}");
119
+ }
120
+ function extractVueStyles(filePath) {
121
+ try {
122
+ const { descriptor } = parse(readFileSync(filePath, "utf8"), { filename: filePath });
123
+ const styles = [];
124
+ const scopeId = createHash("sha256").update(filePath).digest("hex").slice(0, 8);
125
+ for (let i = 0; i < descriptor.styles.length; i++) {
126
+ const style = descriptor.styles[i];
127
+ const result = compileStyle({
128
+ source: style.content,
129
+ filename: filePath,
130
+ id: `data-v-${scopeId}`,
131
+ scoped: style.scoped
132
+ });
133
+ if (!result.errors.length && result.code) styles.push(normalizeCSSContent(result.code));
134
+ }
135
+ return styles;
136
+ } catch {
137
+ return [];
138
+ }
139
+ }
140
+ var SSRStylesPlugin = class {
141
+ nuxt;
142
+ clientCSSByIssuer = /* @__PURE__ */ new Map();
143
+ chunksWithInlinedCSS = /* @__PURE__ */ new Set();
144
+ globalCSSPaths = /* @__PURE__ */ new Set();
145
+ constructor(nuxt) {
146
+ this.nuxt = nuxt;
147
+ this.globalCSSPaths = this.resolveGlobalCSS();
148
+ nuxt.hook("build:manifest", (manifest) => {
149
+ for (const [id, chunk] of Object.entries(manifest)) {
150
+ if (chunk.isEntry && chunk.src) this.chunksWithInlinedCSS.add(chunk.src);
151
+ else if (this.chunksWithInlinedCSS.has(id)) chunk.css &&= [];
152
+ if (chunk.css?.length) chunk.css = chunk.css.filter((cssPath) => {
153
+ for (const globalPath of this.globalCSSPaths) if (cssPath.includes(globalPath.split("/").pop() || "")) return false;
154
+ return true;
155
+ });
156
+ }
157
+ });
158
+ }
159
+ shouldInline(mod) {
160
+ const shouldInline = this.nuxt.options.features.inlineStyles;
161
+ if (typeof shouldInline === "boolean") return shouldInline;
162
+ return shouldInline(mod.identifier());
163
+ }
164
+ escapeTemplateLiteral(str) {
165
+ return str.replace(/[`\\$]/g, (m) => m === "$" ? "\\$" : `\\${m}`);
166
+ }
167
+ isBuildAsset(url) {
168
+ const buildDir = withTrailingSlash(this.nuxt.options.app.buildAssetsDir || "/_nuxt/");
169
+ return url.startsWith(buildDir);
170
+ }
171
+ isPublicAsset(url, nitro) {
172
+ const cleaned = url.replace(/[?#].*$/, "");
173
+ for (const dir of nitro.options.publicAssets) {
174
+ const base = withTrailingSlash(dir.baseURL || "/");
175
+ if (!url.startsWith(base)) continue;
176
+ if (existsSync(cleaned.replace(base, withTrailingSlash(dir.dir)))) return true;
177
+ }
178
+ return false;
179
+ }
180
+ rewriteStyle(css, nitro) {
181
+ let changed = false;
182
+ let needsPublicAsset = false;
183
+ let needsBuildAsset = false;
184
+ let lastIndex = 0;
185
+ let out = "`";
186
+ for (const match of css.matchAll(CSS_URL_RE)) {
187
+ const index = match.index ?? 0;
188
+ const before = css.slice(lastIndex, index);
189
+ if (before) out += this.escapeTemplateLiteral(before);
190
+ const full = match[0];
191
+ const rawUrl = match[2] || "";
192
+ const stripped = rawUrl.replace(/[?#].*$/, "");
193
+ if (this.isPublicAsset(stripped, nitro)) {
194
+ needsPublicAsset = true;
195
+ changed = true;
196
+ out += "${publicAssetsURL(" + JSON.stringify(rawUrl) + ")}";
197
+ } else if (this.isBuildAsset(stripped)) {
198
+ needsBuildAsset = true;
199
+ changed = true;
200
+ out += "${buildAssetsURL(" + JSON.stringify(rawUrl) + ")}";
201
+ } else out += this.escapeTemplateLiteral(full);
202
+ lastIndex = index + full.length;
203
+ }
204
+ const tail = css.slice(lastIndex);
205
+ if (tail) out += this.escapeTemplateLiteral(tail);
206
+ out += "`";
207
+ return {
208
+ code: changed ? out : JSON.stringify(css),
209
+ needsPublicAsset,
210
+ needsBuildAsset
211
+ };
212
+ }
213
+ resolveGlobalCSS() {
214
+ const req = createRequire(this.nuxt.options.rootDir);
215
+ const resolved = /* @__PURE__ */ new Set();
216
+ const entries = this.nuxt.options.css || [];
217
+ for (const entry of entries) {
218
+ const src = typeof entry === "string" ? entry : entry?.src;
219
+ if (!src) continue;
220
+ const path = this.resolveCSSRequest(src, req);
221
+ if (path) resolved.add(path);
222
+ }
223
+ return resolved;
224
+ }
225
+ resolveCSSRequest(request, req) {
226
+ const candidates = /* @__PURE__ */ new Set();
227
+ const resolved = resolveAlias(request, this.nuxt.options.alias);
228
+ if (isAbsolute(resolved)) candidates.add(resolved);
229
+ else candidates.add(resolve(this.nuxt.options.srcDir, resolved));
230
+ try {
231
+ candidates.add(req.resolve(request));
232
+ } catch {}
233
+ for (const candidate of candidates) {
234
+ const path = resolveFilePath(candidate);
235
+ if (path) return path;
236
+ }
237
+ return null;
238
+ }
239
+ normalizeResourcePath(resource) {
240
+ if (!resource) return null;
241
+ const withoutQuery = resource.split("?")[0];
242
+ return resolveFilePath(withoutQuery);
243
+ }
244
+ apply(compiler) {
245
+ if (this.nuxt.options.dev) return;
246
+ const isClient = compiler.options.name === "client";
247
+ const isServer = compiler.options.name === "server";
248
+ if (!isClient && !isServer) return;
249
+ compiler.hooks.thisCompilation.tap("SSRStylesPlugin", (compilation) => {
250
+ this.collectCSS(compilation);
251
+ if (isClient) this.removeGlobalCSSFromClient(compilation);
252
+ if (isServer) this.emitServerStyles(compilation);
253
+ });
254
+ }
255
+ emitServerStyles(compilation) {
256
+ const { webpack } = compilation.compiler;
257
+ const stage = webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE;
258
+ compilation.hooks.processAssets.tap({
259
+ name: "SSRStylesPlugin",
260
+ stage
261
+ }, () => {
262
+ const nitro = useNitro();
263
+ const collected = new Map(this.clientCSSByIssuer);
264
+ const entryModules = /* @__PURE__ */ new Set();
265
+ for (const entrypoint of compilation.entrypoints.values()) {
266
+ const primaryChunk = typeof entrypoint.getEntrypointChunk === "function" ? entrypoint.getEntrypointChunk() : void 0;
267
+ const chunks = primaryChunk ? [primaryChunk] : entrypoint.chunks;
268
+ for (const chunk of chunks) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) if ("resource" in mod && typeof mod.resource === "string") {
269
+ const resolved = resolveFilePath(mod.resource);
270
+ if (resolved) {
271
+ const rel = normalizePath(this.nuxt, resolved);
272
+ if (rel) entryModules.add(rel);
273
+ else entryModules.add(resolved);
274
+ }
275
+ }
276
+ }
277
+ for (const module of compilation.modules) {
278
+ const resource = module.resource;
279
+ if (!resource || !isVueFile(resource)) continue;
280
+ const rel = normalizePath(this.nuxt, resource);
281
+ if (!rel) continue;
282
+ if (collected.has(rel)) continue;
283
+ const vueStyles = extractVueStyles(resolveFilePath(resource) || resource);
284
+ if (vueStyles.length) collected.set(rel, new Set(vueStyles));
285
+ }
286
+ const emitted = {};
287
+ const rawSource = webpack.sources.RawSource;
288
+ for (const [rel, cssSet] of collected.entries()) {
289
+ if (!cssSet.size) continue;
290
+ const transformed = Array.from(cssSet).map((style) => this.rewriteStyle(style, nitro));
291
+ const needsPublicAssets = transformed.some((t) => t.needsPublicAsset);
292
+ const needsBuildAssets = transformed.some((t) => t.needsBuildAsset);
293
+ const imports = [];
294
+ if (needsPublicAssets || needsBuildAssets) {
295
+ const names = [];
296
+ if (needsBuildAssets) names.push("buildAssetsURL");
297
+ if (needsPublicAssets) names.push("publicAssetsURL");
298
+ imports.push(`import { ${names.join(", ")} } from '#internal/nuxt/paths'`);
299
+ }
300
+ const moduleSource = [...imports, `export default ${genArrayFromRaw(transformed.map((t) => t.code))}`].filter(Boolean).join("\n");
301
+ const styleModuleName = `${sanitizeStyleAssetName(rel)}-styles.mjs`;
302
+ compilation.emitAsset(styleModuleName, new rawSource(moduleSource));
303
+ emitted[rel] = styleModuleName;
304
+ this.chunksWithInlinedCSS.add(rel);
305
+ }
306
+ const stylesSource = ["const interopDefault = r => r.default || r || []", `export default ${genObjectFromRawEntries(Object.entries(emitted).map(([key, value]) => [key, `() => import('./${value}').then(interopDefault)`]))}`].join("\n");
307
+ compilation.emitAsset("styles.mjs", new rawSource(stylesSource));
308
+ const entryIds = Array.from(this.chunksWithInlinedCSS).filter((id) => entryModules.has(id));
309
+ nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(entryIds)}`;
310
+ nitro.options._config.virtual ||= {};
311
+ nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
312
+ });
313
+ }
314
+ findIssuerPath(compilation, mod) {
315
+ let issuer = compilation.moduleGraph.getIssuer(mod);
316
+ while (issuer) {
317
+ if ("resource" in issuer && typeof issuer.resource === "string") return issuer.resource;
318
+ issuer = compilation.moduleGraph.getIssuer(issuer);
319
+ }
320
+ return null;
321
+ }
322
+ removeGlobalCSSFromClient(compilation) {
323
+ compilation.hooks.processAssets.tap({
324
+ name: "SSRStylesPlugin:RemoveGlobalCSS",
325
+ stage: 650
326
+ }, () => {
327
+ for (const chunk of compilation.chunks) if (chunk.name === "nuxt-global-css") {
328
+ const cssAssets = [];
329
+ for (const file of Array.from(chunk.files)) {
330
+ const filename = String(file);
331
+ if (isCSSLike(filename)) {
332
+ const source = compilation.getAsset(filename)?.source;
333
+ const content = source && typeof source.source === "function" ? source.source() : null;
334
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
335
+ if (text) cssAssets.push(text);
336
+ }
337
+ }
338
+ if (cssAssets.length > 0) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
339
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
340
+ const normalized = normalizePath(this.nuxt, issuerPath);
341
+ if (!normalized) continue;
342
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
343
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
344
+ this.clientCSSByIssuer.set(normalized, set);
345
+ }
346
+ for (const file of Array.from(chunk.files)) {
347
+ const filename = String(file);
348
+ if (isCSSLike(filename)) {
349
+ compilation.deleteAsset(filename);
350
+ chunk.files.delete(file);
351
+ }
352
+ }
353
+ }
354
+ });
355
+ }
356
+ collectCSS(compilation) {
357
+ const { webpack } = compilation.compiler;
358
+ const stage = compilation.compiler.options.name === "server" ? webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS : webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER;
359
+ const chunkCSSMeta = /* @__PURE__ */ new Map();
360
+ compilation.hooks.processAssets.tap({
361
+ name: "SSRStylesPlugin",
362
+ stage
363
+ }, () => {
364
+ const cssAssetsByChunk = /* @__PURE__ */ new Map();
365
+ for (const chunk of compilation.chunks) {
366
+ const cssAssets = [];
367
+ const chunkCSSFiles = [];
368
+ for (const file of chunk.files) {
369
+ if (!isCSSLike(file)) continue;
370
+ chunkCSSFiles.push(file);
371
+ const source = compilation.getAsset(file)?.source;
372
+ const content = source && typeof source.source === "function" ? source.source() : null;
373
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
374
+ if (text) cssAssets.push(text);
375
+ }
376
+ if (chunkCSSFiles.length) {
377
+ const chunkCSSModules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk));
378
+ chunkCSSMeta.set(chunk, {
379
+ files: chunkCSSFiles,
380
+ modules: chunkCSSModules
381
+ });
382
+ }
383
+ if (cssAssets.length) cssAssetsByChunk.set(chunk, cssAssets);
384
+ }
385
+ for (const [chunk, cssAssets] of cssAssetsByChunk) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
386
+ if (!this.shouldInline(mod)) continue;
387
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
388
+ const normalized = normalizePath(this.nuxt, issuerPath);
389
+ if (!normalized) continue;
390
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
391
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
392
+ this.clientCSSByIssuer.set(normalized, set);
393
+ }
394
+ for (const mod of compilation.modules) {
395
+ if (!this.shouldInline(mod)) continue;
396
+ const issuerPath = this.findIssuerPath(compilation, mod);
397
+ const normalized = normalizePath(this.nuxt, issuerPath);
398
+ if (!normalized) continue;
399
+ const cssChunks = this.getModuleCSS(mod, compilation);
400
+ if (!cssChunks.length) continue;
401
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
402
+ set.add(cssChunks.join("\n"));
403
+ this.clientCSSByIssuer.set(normalized, set);
404
+ }
405
+ });
406
+ }
407
+ getModuleCSS(mod, _compilation) {
408
+ const cssModule = mod;
409
+ const cssChunks = [];
410
+ if (mod.type === "css/mini-extract" && Array.isArray(cssModule.content)) for (const part of cssModule.content) {
411
+ const css = part?.[1];
412
+ if (css && typeof css === "string") cssChunks.push(normalizeCSSContent(css));
413
+ }
414
+ return cssChunks;
415
+ }
416
+ };
85
417
  function createMFS() {
86
- const fs = createFsFromVolume(new Volume());
87
- const _fs = { ...fs };
88
- _fs.join = join;
89
- _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
90
- _fs.readFile = pify(_fs.readFile);
91
- return _fs;
418
+ const _fs = { ...createFsFromVolume(new Volume()) };
419
+ _fs.join = join;
420
+ _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
421
+ _fs.readFile = pify(_fs.readFile);
422
+ return _fs;
92
423
  }
93
-
94
424
  function toArray(value) {
95
- return Array.isArray(value) ? value : [value];
425
+ return Array.isArray(value) ? value : [value];
96
426
  }
97
-
98
427
  function createWebpackConfigContext(nuxt) {
99
- return {
100
- nuxt,
101
- options: nuxt.options,
102
- userConfig: nuxt.options.webpack,
103
- config: {},
104
- name: "base",
105
- isDev: nuxt.options.dev,
106
- isServer: false,
107
- isClient: false,
108
- alias: {},
109
- transpile: []
110
- };
428
+ return {
429
+ nuxt,
430
+ options: nuxt.options,
431
+ userConfig: nuxt.options.webpack,
432
+ config: {},
433
+ name: "base",
434
+ isDev: nuxt.options.dev,
435
+ isServer: false,
436
+ isClient: false,
437
+ alias: {},
438
+ transpile: []
439
+ };
111
440
  }
112
441
  async function applyPresets(ctx, presets) {
113
- for (const preset of toArray(presets)) {
114
- if (Array.isArray(preset)) {
115
- await preset[0](ctx, preset[1]);
116
- } else {
117
- await preset(ctx);
118
- }
119
- }
442
+ for (const preset of toArray(presets)) if (Array.isArray(preset)) await preset[0](ctx, preset[1]);
443
+ else await preset(ctx);
120
444
  }
121
445
  function fileName(ctx, key) {
122
- let fileName2 = ctx.userConfig.filenames[key];
123
- if (typeof fileName2 === "function") {
124
- fileName2 = fileName2(ctx);
125
- }
126
- if (typeof fileName2 === "string" && ctx.options.dev) {
127
- const hash = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName2);
128
- if (hash) {
129
- logger.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
130
- }
131
- }
132
- return fileName2;
446
+ let fileName = ctx.userConfig.filenames[key];
447
+ if (typeof fileName === "function") fileName = fileName(ctx);
448
+ if (typeof fileName === "string" && ctx.options.dev) {
449
+ const hash = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName);
450
+ if (hash) logger.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
451
+ }
452
+ return fileName;
133
453
  }
134
-
135
454
  function assets(ctx) {
136
- ctx.config.module.rules.push(
137
- {
138
- test: /\.(png|jpe?g|gif|svg|webp)$/i,
139
- use: [{
140
- loader: "url-loader",
141
- options: {
142
- ...ctx.userConfig.loaders.imgUrl,
143
- name: fileName(ctx, "img")
144
- }
145
- }]
146
- },
147
- {
148
- test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
149
- use: [{
150
- loader: "url-loader",
151
- options: {
152
- ...ctx.userConfig.loaders.fontUrl,
153
- name: fileName(ctx, "font")
154
- }
155
- }]
156
- },
157
- {
158
- test: /\.(webm|mp4|ogv)$/i,
159
- use: [{
160
- loader: "file-loader",
161
- options: {
162
- ...ctx.userConfig.loaders.file,
163
- name: fileName(ctx, "video")
164
- }
165
- }]
166
- }
167
- );
455
+ ctx.config.module.rules.push({
456
+ test: /\.(png|jpe?g|gif|svg|webp)$/i,
457
+ use: [{
458
+ loader: "url-loader",
459
+ options: {
460
+ ...ctx.userConfig.loaders.imgUrl,
461
+ name: fileName(ctx, "img")
462
+ }
463
+ }]
464
+ }, {
465
+ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
466
+ use: [{
467
+ loader: "url-loader",
468
+ options: {
469
+ ...ctx.userConfig.loaders.fontUrl,
470
+ name: fileName(ctx, "font")
471
+ }
472
+ }]
473
+ }, {
474
+ test: /\.(webm|mp4|ogv)$/i,
475
+ use: [{
476
+ loader: "file-loader",
477
+ options: {
478
+ ...ctx.userConfig.loaders.file,
479
+ name: fileName(ctx, "video")
480
+ }
481
+ }]
482
+ });
168
483
  }
169
-
170
- class WarningIgnorePlugin {
171
- filter;
172
- constructor(filter) {
173
- this.filter = filter;
174
- }
175
- apply(compiler) {
176
- compiler.hooks.done.tap("warnfix-plugin", (stats) => {
177
- stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
178
- });
179
- }
180
- }
181
-
484
+ var WarningIgnorePlugin = class {
485
+ filter;
486
+ constructor(filter) {
487
+ this.filter = filter;
488
+ }
489
+ apply(compiler) {
490
+ compiler.hooks.done.tap("warnfix-plugin", (stats) => {
491
+ stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
492
+ });
493
+ }
494
+ };
182
495
  const validate = (compiler) => {
183
- if (compiler.options.target !== "node") {
184
- logger.warn('webpack config `target` should be "node".');
185
- }
186
- if (!compiler.options.externals) {
187
- logger.info(
188
- "It is recommended to externalize dependencies in the server build for better build performance."
189
- );
190
- }
496
+ if (compiler.options.target !== "node") logger.warn("webpack config `target` should be \"node\".");
497
+ if (!compiler.options.externals) logger.info("It is recommended to externalize dependencies in the server build for better build performance.");
191
498
  };
192
499
  const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
193
500
  const isJS = (file) => isJSRegExp.test(file);
@@ -195,88 +502,59 @@ const extractQueryPartJS = (file) => isJSRegExp.exec(file)?.[1];
195
502
  const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
196
503
  const isCSS = (file) => isCSSRegExp.test(file);
197
504
  const isHotUpdate = (file) => file.includes("hot-update");
198
-
199
505
  const DYNAMIC_IMPORT_RE = /import\([^)]*\+\s*__webpack_require__[^+]*\)\.then/;
200
506
  const DYNAMIC_IMPORT_REPLACE_RE = /import\([^)]*\+\s*(__webpack_require__[^+]*)\)\.then/g;
201
507
  const HELPER_FILENAME = "_dynamic-import-helper.mjs";
202
- const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";
203
- `;
204
- class RollupCompatDynamicImportPlugin {
205
- apply(compiler) {
206
- compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
207
- compilation.hooks.processAssets.tapAsync(
208
- {
209
- name: "RollupCompatDynamicImportPlugin",
210
- stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
211
- },
212
- (assets, callback) => {
213
- try {
214
- const targetFiles = /* @__PURE__ */ new Set();
215
- for (const chunk of compilation.chunks) {
216
- if (chunk.canBeInitial() || chunk.hasRuntime()) {
217
- for (const file of chunk.files || []) {
218
- targetFiles.add(file);
219
- }
220
- }
221
- }
222
- for (const [filename, asset] of Object.entries(assets)) {
223
- if (!isJS(filename)) {
224
- continue;
225
- }
226
- if (!targetFiles.has(filename)) {
227
- continue;
228
- }
229
- const source = asset.source();
230
- const originalCode = typeof source === "string" ? source : source.toString();
231
- if (!DYNAMIC_IMPORT_RE.test(originalCode)) {
232
- continue;
233
- }
234
- const transformedCode = this.transformDynamicImports(originalCode);
235
- if (transformedCode !== originalCode) {
236
- assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
237
- }
238
- }
239
- this.generateDynamicImportHelper(compilation);
240
- callback();
241
- } catch (error) {
242
- callback(error);
243
- }
244
- }
245
- );
246
- });
247
- }
248
- transformDynamicImports(source) {
249
- let transformed = source;
250
- let needsHelperImport = false;
251
- transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
252
- needsHelperImport = true;
253
- return `_rollupDynamicImport(${filename}).then`;
254
- });
255
- if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) {
256
- transformed = HELPER_IMPORT + transformed;
257
- }
258
- return transformed;
259
- }
260
- generateDynamicImportHelper(compilation) {
261
- const chunkFiles = [];
262
- for (const chunk of compilation.chunks) {
263
- if (chunk.hasRuntime()) {
264
- continue;
265
- }
266
- for (const filename of chunk.files) {
267
- if (filename && isJS(filename)) {
268
- chunkFiles.push(filename);
269
- }
270
- }
271
- }
272
- if (chunkFiles.length === 0) {
273
- return;
274
- }
275
- const helperContent = this.generateHelperContent(chunkFiles);
276
- compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
277
- }
278
- generateHelperContent(chunkFiles) {
279
- return `
508
+ const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";\n`;
509
+ var RollupCompatDynamicImportPlugin = class {
510
+ apply(compiler) {
511
+ compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
512
+ compilation.hooks.processAssets.tapAsync({
513
+ name: "RollupCompatDynamicImportPlugin",
514
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
515
+ }, (assets, callback) => {
516
+ try {
517
+ const targetFiles = /* @__PURE__ */ new Set();
518
+ for (const chunk of compilation.chunks) if (chunk.canBeInitial() || chunk.hasRuntime()) for (const file of chunk.files || []) targetFiles.add(file);
519
+ for (const [filename, asset] of Object.entries(assets)) {
520
+ if (!isJS(filename)) continue;
521
+ if (!targetFiles.has(filename)) continue;
522
+ const source = asset.source();
523
+ const originalCode = typeof source === "string" ? source : source.toString();
524
+ if (!DYNAMIC_IMPORT_RE.test(originalCode)) continue;
525
+ const transformedCode = this.transformDynamicImports(originalCode);
526
+ if (transformedCode !== originalCode) assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
527
+ }
528
+ this.generateDynamicImportHelper(compilation);
529
+ callback();
530
+ } catch (error) {
531
+ callback(error);
532
+ }
533
+ });
534
+ });
535
+ }
536
+ transformDynamicImports(source) {
537
+ let transformed = source;
538
+ let needsHelperImport = false;
539
+ transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
540
+ needsHelperImport = true;
541
+ return `_rollupDynamicImport(${filename}).then`;
542
+ });
543
+ if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) transformed = HELPER_IMPORT + transformed;
544
+ return transformed;
545
+ }
546
+ generateDynamicImportHelper(compilation) {
547
+ const chunkFiles = [];
548
+ for (const chunk of compilation.chunks) {
549
+ if (chunk.hasRuntime()) continue;
550
+ for (const filename of chunk.files) if (filename && isJS(filename)) chunkFiles.push(filename);
551
+ }
552
+ if (chunkFiles.length === 0) return;
553
+ const helperContent = this.generateHelperContent(chunkFiles);
554
+ compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
555
+ }
556
+ generateHelperContent(chunkFiles) {
557
+ return `
280
558
  // Rollup-compatible dynamic import helper generated by webpack
281
559
  // This helper enables rollup to consume webpack chunks directly
282
560
 
@@ -293,1000 +571,878 @@ export function _rollupDynamicImport(chunkId) {
293
571
  return chunk()
294
572
  }
295
573
  `;
296
- }
297
- }
298
-
574
+ }
575
+ };
299
576
  async function base(ctx) {
300
- await applyPresets(ctx, [
301
- baseAlias,
302
- baseConfig,
303
- basePlugins,
304
- baseResolve,
305
- baseTranspile
306
- ]);
577
+ await applyPresets(ctx, [
578
+ baseAlias,
579
+ baseConfig,
580
+ basePlugins,
581
+ baseResolve,
582
+ baseTranspile
583
+ ]);
307
584
  }
308
585
  function baseConfig(ctx) {
309
- ctx.config = defu({}, {
310
- name: ctx.name,
311
- entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
312
- module: { rules: [] },
313
- plugins: [],
314
- externals: [],
315
- optimization: {
316
- ...ctx.userConfig.optimization,
317
- minimizer: []
318
- },
319
- experiments: {
320
- ...ctx.userConfig.experiments
321
- },
322
- mode: ctx.isDev ? "development" : "production",
323
- cache: getCache(ctx),
324
- output: getOutput(ctx),
325
- stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
326
- ...ctx.config
327
- });
586
+ ctx.config = defu({}, {
587
+ name: ctx.name,
588
+ entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
589
+ module: { rules: [] },
590
+ plugins: [],
591
+ externals: [],
592
+ optimization: {
593
+ ...ctx.userConfig.optimization,
594
+ minimizer: []
595
+ },
596
+ experiments: { ...ctx.userConfig.experiments },
597
+ mode: ctx.isDev ? "development" : "production",
598
+ cache: getCache(ctx),
599
+ output: getOutput(ctx),
600
+ stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
601
+ ...ctx.config
602
+ });
328
603
  }
329
604
  function basePlugins(ctx) {
330
- ctx.config.plugins ||= [];
331
- if (ctx.options.dev) {
332
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
333
- ctx.config.plugins.push(new TimeFixPlugin());
334
- }
335
- }
336
- ctx.config.plugins.push(...ctx.userConfig.plugins || []);
337
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
338
- ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
339
- }
340
- ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
341
- if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) {
342
- ctx.config.plugins.push(
343
- new FriendlyErrorsWebpackPlugin({
344
- clearConsole: false,
345
- reporter: "consola",
346
- logLevel: "ERROR"
347
- // TODO
348
- })
349
- );
350
- }
351
- if (ctx.nuxt.options.webpack.profile) {
352
- const colors = {
353
- client: "green",
354
- server: "orange",
355
- modern: "blue"
356
- };
357
- ctx.config.plugins.push(new WebpackBarPlugin({
358
- name: ctx.name,
359
- color: colors[ctx.name],
360
- reporters: ["stats"],
361
- // @ts-expect-error TODO: this is a valid option for Webpack.ProgressPlugin and needs to be declared for WebpackBar
362
- stats: !ctx.isDev,
363
- reporter: {
364
- reporter: {
365
- change: (_, { shortPath }) => {
366
- if (!ctx.isServer) {
367
- ctx.nuxt.callHook(`${builder}:change`, shortPath);
368
- }
369
- },
370
- done: (_, { stats }) => {
371
- if (stats.hasErrors()) {
372
- ctx.nuxt.callHook(`${builder}:error`);
373
- } else {
374
- logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
375
- }
376
- },
377
- allDone: () => {
378
- ctx.nuxt.callHook(`${builder}:done`);
379
- },
380
- progress: ({ webpackbar }) => {
381
- ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
382
- }
383
- }
384
- }
385
- }));
386
- }
387
- if (ctx.isServer && !ctx.isDev) {
388
- ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
389
- }
605
+ ctx.config.plugins ||= [];
606
+ if (ctx.options.dev) {
607
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new TimeFixPlugin());
608
+ }
609
+ ctx.config.plugins.push(...ctx.userConfig.plugins || []);
610
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
611
+ ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
612
+ if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) ctx.config.plugins.push(new FriendlyErrorsWebpackPlugin({
613
+ clearConsole: false,
614
+ reporter: "consola",
615
+ logLevel: "ERROR"
616
+ }));
617
+ if (ctx.nuxt.options.webpack.profile) ctx.config.plugins.push(new WebpackBarPlugin({
618
+ name: ctx.name,
619
+ color: {
620
+ client: "green",
621
+ server: "orange",
622
+ modern: "blue"
623
+ }[ctx.name],
624
+ reporters: ["stats"],
625
+ stats: !ctx.isDev,
626
+ reporter: { reporter: {
627
+ change: (_, { shortPath }) => {
628
+ if (!ctx.isServer) ctx.nuxt.callHook(`${builder}:change`, shortPath);
629
+ },
630
+ done: (_, { stats }) => {
631
+ if (stats.hasErrors()) ctx.nuxt.callHook(`${builder}:error`);
632
+ else logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
633
+ },
634
+ allDone: () => {
635
+ ctx.nuxt.callHook(`${builder}:done`);
636
+ },
637
+ progress: ({ webpackbar }) => {
638
+ ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
639
+ }
640
+ } }
641
+ }));
642
+ if (ctx.isServer && !ctx.isDev) ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
390
643
  }
391
644
  function baseAlias(ctx) {
392
- ctx.alias = {
393
- "#app": ctx.options.appDir,
394
- [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
395
- ...ctx.options.alias,
396
- ...ctx.alias
397
- };
398
- if (ctx.isClient) {
399
- ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
400
- ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
401
- ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
402
- }
645
+ ctx.alias = {
646
+ "#app": ctx.options.appDir,
647
+ [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
648
+ ...ctx.options.alias,
649
+ ...ctx.alias
650
+ };
651
+ if (ctx.isClient) {
652
+ ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
653
+ ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
654
+ ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
655
+ }
403
656
  }
404
657
  function baseResolve(ctx) {
405
- const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
406
- ctx.config.resolve = {
407
- extensions: [".wasm", ".mjs", ".js", ".ts", ".json", ".vue", ".jsx", ".tsx"],
408
- alias: ctx.alias,
409
- modules: webpackModulesDir,
410
- fullySpecified: false,
411
- ...ctx.config.resolve
412
- };
413
- ctx.config.resolveLoader = {
414
- modules: webpackModulesDir,
415
- ...ctx.config.resolveLoader
416
- };
658
+ const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
659
+ ctx.config.resolve = {
660
+ extensions: [
661
+ ".wasm",
662
+ ".mjs",
663
+ ".js",
664
+ ".ts",
665
+ ".json",
666
+ ".vue",
667
+ ".jsx",
668
+ ".tsx"
669
+ ],
670
+ alias: ctx.alias,
671
+ modules: webpackModulesDir,
672
+ fullySpecified: false,
673
+ ...ctx.config.resolve
674
+ };
675
+ ctx.config.resolveLoader = {
676
+ modules: webpackModulesDir,
677
+ ...ctx.config.resolveLoader
678
+ };
417
679
  }
418
680
  function baseTranspile(ctx) {
419
- const transpile = [
420
- /\.vue\.js/i,
421
- // include SFCs in node_modules
422
- /consola\/src/,
423
- /vue-demi/,
424
- /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
425
- ];
426
- for (let pattern of ctx.options.build.transpile) {
427
- if (typeof pattern === "function") {
428
- const result = pattern(ctx);
429
- if (result) {
430
- pattern = result;
431
- }
432
- }
433
- if (typeof pattern === "string") {
434
- transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
435
- } else if (pattern instanceof RegExp) {
436
- transpile.push(pattern);
437
- }
438
- }
439
- ctx.transpile = [...transpile, ...ctx.transpile];
681
+ const transpile = [
682
+ /\.vue\.js/i,
683
+ /consola\/src/,
684
+ /vue-demi/,
685
+ /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
686
+ ];
687
+ for (let pattern of ctx.options.build.transpile) {
688
+ if (typeof pattern === "function") {
689
+ const result = pattern(ctx);
690
+ if (result) pattern = result;
691
+ }
692
+ if (typeof pattern === "string") transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
693
+ else if (pattern instanceof RegExp) transpile.push(pattern);
694
+ }
695
+ ctx.transpile = [...transpile, ...ctx.transpile];
440
696
  }
441
697
  function getCache(ctx) {
442
- if (!ctx.options.dev) {
443
- return false;
444
- }
698
+ if (!ctx.options.dev) return false;
445
699
  }
446
700
  function getOutput(ctx) {
447
- return {
448
- path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
449
- filename: fileName(ctx, "app"),
450
- chunkFilename: fileName(ctx, "chunk"),
451
- publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
452
- };
701
+ return {
702
+ path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
703
+ filename: fileName(ctx, "app"),
704
+ chunkFilename: fileName(ctx, "chunk"),
705
+ publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
706
+ };
453
707
  }
454
708
  function getWarningIgnoreFilter(ctx) {
455
- const filters = [
456
- // Hide warnings about plugins without a default export (#1179)
457
- (warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"),
458
- ...ctx.userConfig.warningIgnoreFilters || []
459
- ];
460
- return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
709
+ const filters = [(warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"), ...ctx.userConfig.warningIgnoreFilters || []];
710
+ return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
461
711
  }
462
712
  function getEnv(ctx) {
463
- const _env = {
464
- "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
465
- "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
466
- "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
467
- "process.env.VUE_ENV": JSON.stringify(ctx.name),
468
- "process.dev": ctx.options.dev,
469
- "process.test": isTest,
470
- "process.browser": ctx.isClient,
471
- "process.client": ctx.isClient,
472
- "process.server": ctx.isServer,
473
- "import.meta.dev": ctx.options.dev,
474
- "import.meta.test": isTest,
475
- "import.meta.browser": ctx.isClient,
476
- "import.meta.client": ctx.isClient,
477
- "import.meta.server": ctx.isServer
478
- };
479
- if (ctx.isClient) {
480
- _env["process.prerender"] = false;
481
- _env["process.nitro"] = false;
482
- _env["import.meta.prerender"] = false;
483
- _env["import.meta.nitro"] = false;
484
- } else {
485
- _env["process.prerender"] = "(()=>process.prerender)()";
486
- _env["process.nitro"] = "(()=>process.nitro)()";
487
- _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
488
- _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
489
- }
490
- if (ctx.userConfig.aggressiveCodeRemoval) {
491
- _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
492
- _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
493
- }
494
- return _env;
713
+ const _env = {
714
+ "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
715
+ "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
716
+ "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
717
+ "process.env.VUE_ENV": JSON.stringify(ctx.name),
718
+ "process.dev": ctx.options.dev,
719
+ "process.test": isTest,
720
+ "process.browser": ctx.isClient,
721
+ "process.client": ctx.isClient,
722
+ "process.server": ctx.isServer,
723
+ "import.meta.dev": ctx.options.dev,
724
+ "import.meta.test": isTest,
725
+ "import.meta.browser": ctx.isClient,
726
+ "import.meta.client": ctx.isClient,
727
+ "import.meta.server": ctx.isServer
728
+ };
729
+ if (ctx.isClient) {
730
+ _env["process.prerender"] = false;
731
+ _env["process.nitro"] = false;
732
+ _env["import.meta.prerender"] = false;
733
+ _env["import.meta.nitro"] = false;
734
+ } else {
735
+ _env["process.prerender"] = "(()=>process.prerender)()";
736
+ _env["process.nitro"] = "(()=>process.nitro)()";
737
+ _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
738
+ _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
739
+ }
740
+ if (ctx.userConfig.aggressiveCodeRemoval) {
741
+ _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
742
+ _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
743
+ }
744
+ return _env;
495
745
  }
496
746
  const statsMap = {
497
- silent: "none",
498
- info: "normal",
499
- verbose: "verbose"
747
+ silent: "none",
748
+ info: "normal",
749
+ verbose: "verbose"
500
750
  };
501
-
502
751
  function esbuild(ctx) {
503
- const target = ctx.isServer ? "es2020" : "chrome85";
504
- ctx.config.optimization.minimizer.push(new EsbuildPlugin());
505
- ctx.config.module.rules.push(
506
- {
507
- test: /\.m?[jt]s$/i,
508
- loader: "esbuild-loader",
509
- exclude: (file) => {
510
- const lastSegment = file.split("node_modules", 2)[1];
511
- if (!lastSegment) {
512
- return false;
513
- }
514
- return !ctx.transpile.some((module) => module.test(lastSegment));
515
- },
516
- resolve: {
517
- fullySpecified: false
518
- },
519
- options: {
520
- target,
521
- ...ctx.nuxt.options.webpack.loaders.esbuild,
522
- loader: "ts"
523
- }
524
- },
525
- {
526
- test: /\.m?[jt]sx$/,
527
- loader: "esbuild-loader",
528
- options: {
529
- target,
530
- ...ctx.nuxt.options.webpack.loaders.esbuild,
531
- loader: "tsx"
532
- }
533
- }
534
- );
752
+ const target = ctx.isServer ? "es2020" : "chrome85";
753
+ ctx.config.optimization.minimizer.push(new EsbuildPlugin());
754
+ ctx.config.module.rules.push({
755
+ test: /\.m?[jt]s$/i,
756
+ loader: "esbuild-loader",
757
+ exclude: (file) => {
758
+ const lastSegment = file.split("node_modules", 2)[1];
759
+ if (!lastSegment) return false;
760
+ return !ctx.transpile.some((module) => module.test(lastSegment));
761
+ },
762
+ resolve: { fullySpecified: false },
763
+ options: {
764
+ target,
765
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
766
+ loader: "ts"
767
+ }
768
+ }, {
769
+ test: /\.m?[jt]sx$/,
770
+ loader: "esbuild-loader",
771
+ options: {
772
+ target,
773
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
774
+ loader: "tsx"
775
+ }
776
+ });
535
777
  }
536
-
537
778
  function pug(ctx) {
538
- ctx.config.module.rules.push({
539
- test: /\.pug$/i,
540
- oneOf: [
541
- {
542
- resourceQuery: /^\?vue/i,
543
- use: [{
544
- loader: "pug-plain-loader",
545
- options: ctx.userConfig.loaders.pugPlain
546
- }]
547
- },
548
- {
549
- use: [
550
- "raw-loader",
551
- {
552
- loader: "pug-plain-loader",
553
- options: ctx.userConfig.loaders.pugPlain
554
- }
555
- ]
556
- }
557
- ]
558
- });
779
+ ctx.config.module.rules.push({
780
+ test: /\.pug$/i,
781
+ oneOf: [{
782
+ resourceQuery: /^\?vue/i,
783
+ use: [{
784
+ loader: "pug-plain-loader",
785
+ options: ctx.userConfig.loaders.pugPlain
786
+ }]
787
+ }, { use: ["raw-loader", {
788
+ loader: "pug-plain-loader",
789
+ options: ctx.userConfig.loaders.pugPlain
790
+ }] }]
791
+ });
559
792
  }
560
-
561
793
  const isPureObject = (obj) => obj !== null && !Array.isArray(obj) && typeof obj === "object";
562
794
  function sortPlugins({ plugins, order }) {
563
- const names = Object.keys(plugins);
564
- return typeof order === "function" ? order(names) : order || names;
795
+ const names = Object.keys(plugins);
796
+ return typeof order === "function" ? order(names) : order || names;
565
797
  }
566
798
  async function getPostcssConfig(nuxt) {
567
- if (!nuxt.options.webpack.postcss || !nuxt.options.postcss) {
568
- return false;
569
- }
570
- const postcssOptions = defu({}, nuxt.options.postcss, {
571
- plugins: {
572
- /**
573
- * https://github.com/postcss/postcss-import
574
- */
575
- "postcss-import": {
576
- resolve: createResolver({
577
- alias: { ...nuxt.options.alias },
578
- modules: nuxt.options.modulesDir
579
- })
580
- },
581
- /**
582
- * https://github.com/postcss/postcss-url
583
- */
584
- "postcss-url": {}
585
- },
586
- sourceMap: nuxt.options.webpack.cssSourceMap
587
- });
588
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
589
- if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
590
- const plugins = [];
591
- for (const pluginName of sortPlugins(postcssOptions)) {
592
- const pluginOptions = postcssOptions.plugins[pluginName];
593
- if (!pluginOptions) {
594
- continue;
595
- }
596
- let pluginFn;
597
- for (const parentURL of nuxt.options.modulesDir) {
598
- pluginFn = await jiti.import(pluginName, { parentURL: parentURL.replace(/\/node_modules\/?$/, ""), try: true, default: true });
599
- if (typeof pluginFn === "function") {
600
- plugins.push(pluginFn(pluginOptions));
601
- break;
602
- }
603
- }
604
- if (typeof pluginFn !== "function") {
605
- console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
606
- }
607
- }
608
- postcssOptions.plugins = plugins;
609
- }
610
- return {
611
- sourceMap: nuxt.options.webpack.cssSourceMap,
612
- ...nuxt.options.webpack.postcss,
613
- postcssOptions
614
- };
799
+ if (!nuxt.options.webpack.postcss || !nuxt.options.postcss) return false;
800
+ const postcssOptions = defu({}, nuxt.options.postcss, {
801
+ plugins: {
802
+ "postcss-import": { resolve: createResolver({
803
+ alias: { ...nuxt.options.alias },
804
+ modules: nuxt.options.modulesDir
805
+ }) },
806
+ "postcss-url": {}
807
+ },
808
+ sourceMap: nuxt.options.webpack.cssSourceMap
809
+ });
810
+ const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
811
+ if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
812
+ const plugins = [];
813
+ for (const pluginName of sortPlugins(postcssOptions)) {
814
+ const pluginOptions = postcssOptions.plugins[pluginName];
815
+ if (!pluginOptions) continue;
816
+ let pluginFn;
817
+ for (const parentURL of nuxt.options.modulesDir) {
818
+ pluginFn = await jiti.import(pluginName, {
819
+ parentURL: parentURL.replace(/\/node_modules\/?$/, ""),
820
+ try: true,
821
+ default: true
822
+ });
823
+ if (typeof pluginFn === "function") {
824
+ plugins.push(pluginFn(pluginOptions));
825
+ break;
826
+ }
827
+ }
828
+ if (typeof pluginFn !== "function") console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
829
+ }
830
+ postcssOptions.plugins = plugins;
831
+ }
832
+ return {
833
+ sourceMap: nuxt.options.webpack.cssSourceMap,
834
+ ...nuxt.options.webpack.postcss,
835
+ postcssOptions
836
+ };
615
837
  }
616
-
617
838
  async function style(ctx) {
618
- await applyPresets(ctx, [
619
- loaders,
620
- extractCSS,
621
- minimizer
622
- ]);
839
+ await applyPresets(ctx, [
840
+ loaders,
841
+ extractCSS,
842
+ minimizer
843
+ ]);
623
844
  }
624
845
  function minimizer(ctx) {
625
- if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) {
626
- ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({
627
- ...ctx.userConfig.optimizeCSS
628
- }));
629
- }
846
+ if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({ ...ctx.userConfig.optimizeCSS }));
630
847
  }
631
848
  function extractCSS(ctx) {
632
- const config = ctx.userConfig.extractCSS;
633
- if (!config) {
634
- return;
635
- }
636
- const filename = fileName(ctx, "css");
637
- ctx.config.plugins.push(new MiniCssExtractPlugin({
638
- filename,
639
- chunkFilename: filename,
640
- ...config === true ? {} : config
641
- }));
849
+ const config = ctx.userConfig.extractCSS;
850
+ if (!config) return;
851
+ const filename = fileName(ctx, "css");
852
+ ctx.config.plugins.push(new MiniCssExtractPlugin({
853
+ filename,
854
+ chunkFilename: filename,
855
+ ...config === true ? {} : config
856
+ }));
642
857
  }
643
858
  async function loaders(ctx) {
644
- ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
645
- ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
646
- const lessLoader = { loader: "less-loader", options: ctx.userConfig.loaders.less };
647
- ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
648
- const sassLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.sass };
649
- ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
650
- const scssLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.scss };
651
- ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
652
- const stylusLoader = { loader: "stylus-loader", options: ctx.userConfig.loaders.stylus };
653
- ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
859
+ ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
860
+ ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
861
+ const lessLoader = {
862
+ loader: "less-loader",
863
+ options: ctx.userConfig.loaders.less
864
+ };
865
+ ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
866
+ const sassLoader = {
867
+ loader: "sass-loader",
868
+ options: ctx.userConfig.loaders.sass
869
+ };
870
+ ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
871
+ const scssLoader = {
872
+ loader: "sass-loader",
873
+ options: ctx.userConfig.loaders.scss
874
+ };
875
+ ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
876
+ const stylusLoader = {
877
+ loader: "stylus-loader",
878
+ options: ctx.userConfig.loaders.stylus
879
+ };
880
+ ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
654
881
  }
655
882
  async function createdStyleRule(lang, test, processorLoader, ctx) {
656
- const styleLoaders = [
657
- await createPostcssLoadersRule(ctx),
658
- processorLoader
659
- ].filter(Boolean);
660
- ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
661
- const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
662
- const cssModuleLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules);
663
- return {
664
- test,
665
- oneOf: [
666
- // This matches <style module>
667
- {
668
- resourceQuery: /module/,
669
- use: cssModuleLoaders.concat(styleLoaders)
670
- },
671
- // This matches plain <style> or <style scoped>
672
- {
673
- use: cssLoaders.concat(styleLoaders)
674
- }
675
- ]
676
- };
883
+ const styleLoaders = [await createPostcssLoadersRule(ctx), processorLoader].filter(Boolean);
884
+ ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
885
+ const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
886
+ return {
887
+ test,
888
+ oneOf: [{
889
+ resourceQuery: /module/,
890
+ use: createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules).concat(styleLoaders)
891
+ }, { use: cssLoaders.concat(styleLoaders) }]
892
+ };
677
893
  }
678
894
  function createCssLoadersRule(ctx, cssLoaderOptions) {
679
- const cssLoader = { loader: "css-loader", options: cssLoaderOptions };
680
- if (ctx.userConfig.extractCSS) {
681
- if (ctx.isServer) {
682
- if (cssLoader.options.modules) {
683
- cssLoader.options.modules.exportOnlyLocals ??= true;
684
- }
685
- return [cssLoader];
686
- }
687
- return [
688
- {
689
- loader: MiniCssExtractPlugin.loader
690
- },
691
- cssLoader
692
- ];
693
- }
694
- return [
695
- // https://github.com/vuejs/vue-style-loader/issues/56
696
- // {
697
- // loader: 'vue-style-loader',
698
- // options: options.webpack.loaders.vueStyle
699
- // },
700
- cssLoader
701
- ];
895
+ const cssLoader = {
896
+ loader: "css-loader",
897
+ options: cssLoaderOptions
898
+ };
899
+ if (ctx.userConfig.extractCSS) {
900
+ if (ctx.isServer) {
901
+ if (cssLoader.options.modules) cssLoader.options.modules.exportOnlyLocals ??= true;
902
+ return [cssLoader];
903
+ }
904
+ return [{ loader: MiniCssExtractPlugin.loader }, cssLoader];
905
+ }
906
+ return [cssLoader];
702
907
  }
703
908
  async function createPostcssLoadersRule(ctx) {
704
- if (!ctx.options.postcss) {
705
- return;
706
- }
707
- const config = await getPostcssConfig(ctx.nuxt);
708
- if (!config) {
709
- return;
710
- }
711
- return {
712
- loader: "postcss-loader",
713
- options: config
714
- };
715
- }
716
-
717
- class VueSSRClientPlugin {
718
- serverDist;
719
- nuxt;
720
- constructor(options) {
721
- this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
722
- this.nuxt = options.nuxt;
723
- }
724
- apply(compiler) {
725
- compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
726
- const stats = compilation.getStats().toJson();
727
- const initialFiles = /* @__PURE__ */ new Set();
728
- for (const { assets } of Object.values(stats.entrypoints)) {
729
- if (!assets) {
730
- continue;
731
- }
732
- for (const asset of assets) {
733
- const file = asset.name;
734
- if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) {
735
- initialFiles.add(file);
736
- }
737
- }
738
- }
739
- const allFiles = /* @__PURE__ */ new Set();
740
- const asyncFiles = /* @__PURE__ */ new Set();
741
- const assetsMapping = {};
742
- for (const { name: file, chunkNames = [] } of stats.assets) {
743
- if (isHotUpdate(file)) {
744
- continue;
745
- }
746
- allFiles.add(file);
747
- const isFileJS = isJS(file);
748
- if (!initialFiles.has(file) && (isFileJS || isCSS(file))) {
749
- asyncFiles.add(file);
750
- }
751
- if (isFileJS) {
752
- const componentHash = hash(chunkNames.join("|"));
753
- const map = assetsMapping[componentHash] ||= [];
754
- map.push(file);
755
- }
756
- }
757
- const webpackManifest = {
758
- publicPath: stats.publicPath,
759
- all: [...allFiles],
760
- initial: [...initialFiles],
761
- async: [...asyncFiles],
762
- modules: {
763
- /* [identifier: string]: Array<index: number> */
764
- },
765
- assetsMapping
766
- };
767
- const { entrypoints = {}, namedChunkGroups = {} } = stats;
768
- const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
769
- for (const m of stats.modules) {
770
- if (m.chunks?.length !== 1) {
771
- continue;
772
- }
773
- const [cid] = m.chunks;
774
- const chunk = stats.chunks.find((c) => c.id === cid);
775
- if (!chunk || !chunk.files || !cid) {
776
- continue;
777
- }
778
- const id = m.identifier.replace(/\s\w+$/, "");
779
- const filesSet = /* @__PURE__ */ new Set();
780
- for (const file of chunk.files) {
781
- const index = fileToIndex(file);
782
- if (index !== -1) {
783
- filesSet.add(index);
784
- }
785
- }
786
- for (const chunkName of chunk.names) {
787
- if (!entrypoints[chunkName]) {
788
- const chunkGroup = namedChunkGroups[chunkName];
789
- if (chunkGroup) {
790
- for (const asset of chunkGroup.assets) {
791
- filesSet.add(fileToIndex(asset.name));
792
- }
793
- }
794
- }
795
- }
796
- const files = Array.from(filesSet);
797
- webpackManifest.modules[hash(id)] = files;
798
- if (Array.isArray(m.modules)) {
799
- for (const concatenatedModule of m.modules) {
800
- const id2 = hash(concatenatedModule.identifier.replace(/\s\w+$/, ""));
801
- webpackManifest.modules[id2] ||= files;
802
- }
803
- }
804
- if (stats.modules) {
805
- for (const m2 of stats.modules) {
806
- if (m2.assets?.length && m2.chunks?.includes(cid)) {
807
- files.push(...m2.assets.map(fileToIndex));
808
- }
809
- }
810
- }
811
- }
812
- const manifest = normalizeWebpackManifest(webpackManifest);
813
- await this.nuxt.callHook("build:manifest", manifest);
814
- await mkdir(this.serverDist, { recursive: true });
815
- const precomputed = precomputeDependencies(manifest);
816
- await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
817
- await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
818
- await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
819
- });
820
- }
909
+ if (!ctx.options.postcss) return;
910
+ const config = await getPostcssConfig(ctx.nuxt);
911
+ if (!config) return;
912
+ return {
913
+ loader: "postcss-loader",
914
+ options: config
915
+ };
821
916
  }
822
-
917
+ var VueSSRClientPlugin = class {
918
+ serverDist;
919
+ nuxt;
920
+ constructor(options) {
921
+ this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
922
+ this.nuxt = options.nuxt;
923
+ }
924
+ getRelativeModuleId(identifier, context) {
925
+ const id = identifier.replace(/\s\w+$/, "");
926
+ const resourceMatch = id.match(/([^!]*\.vue)(?:\?|$)/);
927
+ return resourceMatch && resourceMatch[1] ? normalize(relative(context, resourceMatch[1])).replace(/^\.\//, "").replace(/\\/g, "/") : id;
928
+ }
929
+ apply(compiler) {
930
+ compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
931
+ const stats = compilation.getStats().toJson();
932
+ const context = this.nuxt.options.srcDir;
933
+ const initialFiles = /* @__PURE__ */ new Set();
934
+ for (const { assets } of Object.values(stats.entrypoints)) {
935
+ if (!assets) continue;
936
+ for (const asset of assets) {
937
+ const file = asset.name;
938
+ if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) initialFiles.add(file);
939
+ }
940
+ }
941
+ const allFiles = /* @__PURE__ */ new Set();
942
+ const asyncFiles = /* @__PURE__ */ new Set();
943
+ const assetsMapping = {};
944
+ for (const { name: file, chunkNames = [] } of stats.assets) {
945
+ if (isHotUpdate(file)) continue;
946
+ allFiles.add(file);
947
+ const isFileJS = isJS(file);
948
+ if (!initialFiles.has(file) && (isFileJS || isCSS(file))) asyncFiles.add(file);
949
+ if (isFileJS) {
950
+ const componentHash = hash(chunkNames.join("|"));
951
+ (assetsMapping[componentHash] ||= []).push(file);
952
+ }
953
+ }
954
+ const webpackManifest = {
955
+ publicPath: stats.publicPath,
956
+ all: [...allFiles],
957
+ initial: [...initialFiles],
958
+ async: [...asyncFiles],
959
+ modules: {},
960
+ assetsMapping
961
+ };
962
+ const { entrypoints = {}, namedChunkGroups = {} } = stats;
963
+ const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
964
+ for (const m of stats.modules) {
965
+ if (m.chunks?.length !== 1) continue;
966
+ const [cid] = m.chunks;
967
+ const chunk = stats.chunks.find((c) => c.id === cid);
968
+ if (!chunk || !chunk.files || !cid) continue;
969
+ const relativeId = this.getRelativeModuleId(m.identifier, context);
970
+ const filesSet = /* @__PURE__ */ new Set();
971
+ for (const file of chunk.files) {
972
+ const index = fileToIndex(file);
973
+ if (index !== -1) filesSet.add(index);
974
+ }
975
+ for (const chunkName of chunk.names) if (!entrypoints[chunkName]) {
976
+ const chunkGroup = namedChunkGroups[chunkName];
977
+ if (chunkGroup) for (const asset of chunkGroup.assets) filesSet.add(fileToIndex(asset.name));
978
+ }
979
+ const files = Array.from(filesSet);
980
+ webpackManifest.modules[relativeId] = files;
981
+ if (Array.isArray(m.modules)) for (const concatenatedModule of m.modules) {
982
+ const relativeId = this.getRelativeModuleId(concatenatedModule.identifier, context);
983
+ webpackManifest.modules[relativeId] ||= files;
984
+ }
985
+ if (stats.modules) {
986
+ for (const m of stats.modules) if (m.assets?.length && m.chunks?.includes(cid)) files.push(...m.assets.map(fileToIndex));
987
+ }
988
+ }
989
+ const manifest = normalizeWebpackManifest(webpackManifest);
990
+ await this.nuxt.callHook("build:manifest", manifest);
991
+ await mkdir(this.serverDist, { recursive: true });
992
+ const precomputed = precomputeDependencies(manifest);
993
+ await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
994
+ await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
995
+ await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
996
+ });
997
+ }
998
+ };
823
999
  const JS_MAP_RE = /\.js\.map$/;
824
- class VueSSRServerPlugin {
825
- options;
826
- constructor(options = {}) {
827
- this.options = Object.assign({
828
- filename: null
829
- }, options);
830
- }
831
- apply(compiler) {
832
- validate(compiler);
833
- compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
834
- compilation.hooks.processAssets.tapAsync({
835
- name: "VueSSRServerPlugin",
836
- stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
837
- }, (assets, cb) => {
838
- const stats = compilation.getStats().toJson();
839
- const [entryName] = Object.keys(stats.entrypoints);
840
- const entryInfo = stats.entrypoints[entryName];
841
- if (!entryInfo) {
842
- return cb();
843
- }
844
- const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
845
- if (entryAssets.length > 1) {
846
- throw new Error(
847
- "Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config."
848
- );
849
- }
850
- const [entry] = entryAssets;
851
- if (!entry || typeof entry.name !== "string") {
852
- throw new Error(
853
- `Entry "${entryName}" not found. Did you specify the correct entry option?`
854
- );
855
- }
856
- const bundle = {
857
- entry: entry.name,
858
- files: {},
859
- maps: {}
860
- };
861
- for (const asset of stats.assets) {
862
- if (isJS(asset.name)) {
863
- const queryPart = extractQueryPartJS(asset.name);
864
- if (queryPart !== void 0) {
865
- bundle.files[asset.name] = asset.name.replace(queryPart, "");
866
- } else {
867
- bundle.files[asset.name] = asset.name;
868
- }
869
- } else if (JS_MAP_RE.test(asset.name)) {
870
- bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
871
- } else {
872
- delete assets[asset.name];
873
- }
874
- }
875
- const src = JSON.stringify(bundle, null, 2);
876
- assets[this.options.filename] = {
877
- source: () => src,
878
- size: () => src.length
879
- };
880
- const mjsSrc = "export default " + src;
881
- assets[this.options.filename.replace(".json", ".mjs")] = {
882
- source: () => mjsSrc,
883
- map: () => null,
884
- size: () => mjsSrc.length
885
- };
886
- cb();
887
- });
888
- });
889
- }
890
- }
891
-
1000
+ var VueSSRServerPlugin = class {
1001
+ options;
1002
+ constructor(options = {}) {
1003
+ this.options = Object.assign({ filename: null }, options);
1004
+ }
1005
+ apply(compiler) {
1006
+ validate(compiler);
1007
+ compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
1008
+ compilation.hooks.processAssets.tapAsync({
1009
+ name: "VueSSRServerPlugin",
1010
+ stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
1011
+ }, (assets, cb) => {
1012
+ const stats = compilation.getStats().toJson();
1013
+ const [entryName] = Object.keys(stats.entrypoints);
1014
+ const entryInfo = stats.entrypoints[entryName];
1015
+ if (!entryInfo) return cb();
1016
+ const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
1017
+ if (entryAssets.length > 1) throw new Error("Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config.");
1018
+ const [entry] = entryAssets;
1019
+ if (!entry || typeof entry.name !== "string") throw new Error(`Entry "${entryName}" not found. Did you specify the correct entry option?`);
1020
+ const bundle = {
1021
+ entry: entry.name,
1022
+ files: {},
1023
+ maps: {}
1024
+ };
1025
+ for (const asset of stats.assets) if (isJS(asset.name)) {
1026
+ const queryPart = extractQueryPartJS(asset.name);
1027
+ if (queryPart !== void 0) bundle.files[asset.name] = asset.name.replace(queryPart, "");
1028
+ else bundle.files[asset.name] = asset.name;
1029
+ } else if (JS_MAP_RE.test(asset.name)) bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
1030
+ else delete assets[asset.name];
1031
+ const src = JSON.stringify(bundle, null, 2);
1032
+ assets[this.options.filename] = {
1033
+ source: () => src,
1034
+ size: () => src.length
1035
+ };
1036
+ const mjsSrc = "export default " + src;
1037
+ assets[this.options.filename.replace(".json", ".mjs")] = {
1038
+ source: () => mjsSrc,
1039
+ map: () => null,
1040
+ size: () => mjsSrc.length
1041
+ };
1042
+ cb();
1043
+ });
1044
+ });
1045
+ }
1046
+ };
892
1047
  function vue(ctx) {
893
- ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
894
- ctx.config.module.rules.push({
895
- test: /\.vue$/i,
896
- loader: "vue-loader",
897
- options: ctx.userConfig.loaders.vue
898
- });
899
- if (ctx.isClient) {
900
- ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
901
- } else {
902
- ctx.config.plugins.push(new VueSSRServerPlugin({
903
- filename: `${ctx.name}.manifest.json`
904
- }));
905
- }
906
- ctx.config.plugins.push(new webpack.DefinePlugin({
907
- "__VUE_OPTIONS_API__": "true",
908
- "__VUE_PROD_DEVTOOLS__": "false",
909
- "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
910
- }));
1048
+ ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
1049
+ ctx.config.module.rules.push({
1050
+ test: /\.vue$/i,
1051
+ loader: "vue-loader",
1052
+ options: {
1053
+ ...ctx.userConfig.loaders.vue,
1054
+ isServerBuild: ctx.isServer
1055
+ }
1056
+ });
1057
+ if (ctx.isClient) ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
1058
+ else {
1059
+ ctx.config.plugins.push(new VueSSRServerPlugin({ filename: `${ctx.name}.manifest.json` }));
1060
+ const loaderPath = resolveModulePath("#vue-module-identifier", { from: import.meta.url });
1061
+ ctx.config.module.rules.push({
1062
+ test: /\.vue$/i,
1063
+ enforce: "post",
1064
+ use: [{
1065
+ loader: loaderPath,
1066
+ options: { srcDir: ctx.nuxt.options.srcDir }
1067
+ }]
1068
+ });
1069
+ }
1070
+ ctx.config.plugins.push(new webpack.DefinePlugin({
1071
+ "__VUE_OPTIONS_API__": "true",
1072
+ "__VUE_PROD_DEVTOOLS__": "false",
1073
+ "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
1074
+ }));
911
1075
  }
912
-
913
1076
  async function nuxt(ctx) {
914
- await applyPresets(ctx, [
915
- base,
916
- assets,
917
- esbuild,
918
- pug,
919
- style,
920
- vue
921
- ]);
1077
+ await applyPresets(ctx, [
1078
+ base,
1079
+ assets,
1080
+ esbuild,
1081
+ pug,
1082
+ style,
1083
+ vue
1084
+ ]);
922
1085
  }
923
-
924
1086
  async function client(ctx) {
925
- ctx.name = "client";
926
- ctx.isClient = true;
927
- await applyPresets(ctx, [
928
- nuxt,
929
- clientPlugins,
930
- clientOptimization,
931
- clientDevtool,
932
- clientPerformance,
933
- clientHMR,
934
- clientNodeCompat
935
- ]);
1087
+ ctx.name = "client";
1088
+ ctx.isClient = true;
1089
+ await applyPresets(ctx, [
1090
+ nuxt,
1091
+ clientPlugins,
1092
+ clientOptimization,
1093
+ clientDevtool,
1094
+ clientPerformance,
1095
+ clientHMR,
1096
+ clientNodeCompat
1097
+ ]);
936
1098
  }
937
1099
  function clientDevtool(ctx) {
938
- if (!ctx.nuxt.options.sourcemap.client) {
939
- ctx.config.devtool = false;
940
- return;
941
- }
942
- const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
943
- if (!ctx.isDev) {
944
- ctx.config.devtool = prefix + "source-map";
945
- return;
946
- }
947
- ctx.config.devtool = prefix + "eval-cheap-module-source-map";
1100
+ if (!ctx.nuxt.options.sourcemap.client) {
1101
+ ctx.config.devtool = false;
1102
+ return;
1103
+ }
1104
+ const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
1105
+ if (!ctx.isDev) {
1106
+ ctx.config.devtool = prefix + "source-map";
1107
+ return;
1108
+ }
1109
+ ctx.config.devtool = prefix + "eval-cheap-module-source-map";
948
1110
  }
949
1111
  function clientPerformance(ctx) {
950
- ctx.config.performance = {
951
- maxEntrypointSize: 1e3 * 1024,
952
- hints: ctx.isDev ? false : "warning",
953
- ...ctx.config.performance
954
- };
1112
+ ctx.config.performance = {
1113
+ maxEntrypointSize: 1e3 * 1024,
1114
+ hints: ctx.isDev ? false : "warning",
1115
+ ...ctx.config.performance
1116
+ };
955
1117
  }
956
1118
  function clientNodeCompat(ctx) {
957
- if (!ctx.nuxt.options.experimental.clientNodeCompat) {
958
- return;
959
- }
960
- ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
961
- ctx.config.resolve ||= {};
962
- ctx.config.resolve.fallback = {
963
- ...defineEnv({
964
- nodeCompat: true,
965
- resolve: true
966
- }).env.alias,
967
- ...ctx.config.resolve.fallback
968
- };
969
- ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
970
- resource.request = resource.request.replace(/^node:/, "");
971
- }));
1119
+ if (!ctx.nuxt.options.experimental.clientNodeCompat) return;
1120
+ ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
1121
+ ctx.config.resolve ||= {};
1122
+ ctx.config.resolve.fallback = {
1123
+ ...defineEnv({
1124
+ nodeCompat: true,
1125
+ resolve: true
1126
+ }).env.alias,
1127
+ ...ctx.config.resolve.fallback
1128
+ };
1129
+ ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
1130
+ resource.request = resource.request.replace(/^node:/, "");
1131
+ }));
972
1132
  }
973
1133
  function clientHMR(ctx) {
974
- if (!ctx.isDev) {
975
- return;
976
- }
977
- const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
978
- const hotMiddlewareClientOptions = {
979
- reload: true,
980
- timeout: 3e4,
981
- path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
982
- ...clientOptions,
983
- ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
984
- overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
985
- name: ctx.name
986
- };
987
- const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
988
- const app = ctx.config.entry.app;
989
- app.unshift(
990
- // https://github.com/webpack/webpack-hot-middleware#config
991
- `webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`
992
- );
993
- ctx.config.plugins ||= [];
994
- ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
1134
+ if (!ctx.isDev) return;
1135
+ const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
1136
+ const hotMiddlewareClientOptions = {
1137
+ reload: true,
1138
+ timeout: 3e4,
1139
+ path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
1140
+ ...clientOptions,
1141
+ ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
1142
+ overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
1143
+ name: ctx.name
1144
+ };
1145
+ const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
1146
+ ctx.config.entry.app.unshift(`webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`);
1147
+ ctx.config.plugins ||= [];
1148
+ ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
995
1149
  }
996
- function clientOptimization(_ctx) {
1150
+ function clientOptimization(ctx) {
1151
+ if (!ctx.nuxt.options.features.inlineStyles) return;
1152
+ const globalCSSPaths = /* @__PURE__ */ new Set();
1153
+ for (const css of ctx.options.css) if (typeof css === "string") {
1154
+ const resolved = resolveAlias(css, ctx.options.alias);
1155
+ globalCSSPaths.add(normalize(resolved));
1156
+ }
1157
+ if (globalCSSPaths.size > 0) {
1158
+ ctx.config.optimization ||= {};
1159
+ ctx.config.optimization.splitChunks ||= {};
1160
+ ctx.config.optimization.splitChunks.cacheGroups ||= {};
1161
+ ctx.config.optimization.splitChunks.cacheGroups.nuxtGlobalCSS = {
1162
+ name: "nuxt-global-css",
1163
+ chunks: "all",
1164
+ enforce: true,
1165
+ test: (module) => {
1166
+ if (module.type !== "css/mini-extract") return false;
1167
+ const identifier = normalize(module.identifier());
1168
+ for (const globalPath of globalCSSPaths) if (identifier.includes(globalPath)) return true;
1169
+ return false;
1170
+ }
1171
+ };
1172
+ }
997
1173
  }
998
1174
  function clientPlugins(ctx) {
999
- if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1000
- const statsDir = resolve(ctx.options.analyzeDir);
1001
- ctx.config.plugins.push(new BundleAnalyzerPlugin({
1002
- analyzerMode: "static",
1003
- defaultSizes: "gzip",
1004
- generateStatsFile: true,
1005
- openAnalyzer: true,
1006
- reportFilename: resolve(statsDir, `${ctx.name}.html`),
1007
- statsFilename: resolve(statsDir, `${ctx.name}.json`),
1008
- ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1009
- }));
1010
- }
1011
- if (!ctx.nuxt.options.ssr) {
1012
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1013
- ctx.config.plugins.push(new TsCheckerPlugin({
1014
- logger
1015
- }));
1016
- }
1017
- }
1175
+ if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1176
+ const statsDir = resolve(ctx.options.analyzeDir);
1177
+ ctx.config.plugins.push(new BundleAnalyzerPlugin({
1178
+ analyzerMode: "static",
1179
+ defaultSizes: "gzip",
1180
+ generateStatsFile: true,
1181
+ openAnalyzer: true,
1182
+ reportFilename: resolve(statsDir, `${ctx.name}.html`),
1183
+ statsFilename: resolve(statsDir, `${ctx.name}.json`),
1184
+ ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1185
+ }));
1186
+ }
1187
+ if (!ctx.nuxt.options.ssr) {
1188
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1189
+ }
1018
1190
  }
1019
-
1020
1191
  function node(ctx) {
1021
- ctx.config.target = "node";
1022
- ctx.config.node = false;
1023
- ctx.config.experiments.outputModule = true;
1024
- ctx.config.output = {
1025
- ...ctx.config.output,
1026
- chunkFilename: "[name].mjs",
1027
- chunkFormat: "module",
1028
- chunkLoading: "import",
1029
- module: true,
1030
- environment: {
1031
- module: true,
1032
- arrowFunction: true,
1033
- bigIntLiteral: true,
1034
- const: true,
1035
- destructuring: true,
1036
- dynamicImport: true,
1037
- forOf: true
1038
- },
1039
- library: {
1040
- type: "module"
1041
- }
1042
- };
1043
- ctx.config.performance = {
1044
- ...ctx.config.performance,
1045
- hints: false,
1046
- maxEntrypointSize: Number.POSITIVE_INFINITY,
1047
- maxAssetSize: Number.POSITIVE_INFINITY
1048
- };
1192
+ ctx.config.target = "node";
1193
+ ctx.config.node = false;
1194
+ ctx.config.experiments.outputModule = true;
1195
+ ctx.config.output = {
1196
+ ...ctx.config.output,
1197
+ chunkFilename: "[name].mjs",
1198
+ chunkFormat: "module",
1199
+ chunkLoading: "import",
1200
+ module: true,
1201
+ environment: {
1202
+ module: true,
1203
+ arrowFunction: true,
1204
+ bigIntLiteral: true,
1205
+ const: true,
1206
+ destructuring: true,
1207
+ dynamicImport: true,
1208
+ forOf: true
1209
+ },
1210
+ library: { type: "module" }
1211
+ };
1212
+ ctx.config.performance = {
1213
+ ...ctx.config.performance,
1214
+ hints: false,
1215
+ maxEntrypointSize: Number.POSITIVE_INFINITY,
1216
+ maxAssetSize: Number.POSITIVE_INFINITY
1217
+ };
1049
1218
  }
1050
-
1051
1219
  const assetPattern = /\.(?:css|s[ca]ss|png|jpe?g|gif|svg|woff2?|eot|ttf|otf|webp|webm|mp4|ogv)(?:\?.*)?$/i;
1220
+ const VIRTUAL_RE = /^\0?virtual:(?:nuxt:)?/;
1052
1221
  async function server(ctx) {
1053
- ctx.name = "server";
1054
- ctx.isServer = true;
1055
- await applyPresets(ctx, [
1056
- nuxt,
1057
- node,
1058
- serverStandalone,
1059
- serverPreset,
1060
- serverPlugins
1061
- ]);
1222
+ ctx.name = "server";
1223
+ ctx.isServer = true;
1224
+ await applyPresets(ctx, [
1225
+ nuxt,
1226
+ node,
1227
+ serverStandalone,
1228
+ serverPreset,
1229
+ serverPlugins
1230
+ ]);
1062
1231
  }
1063
1232
  function serverPreset(ctx) {
1064
- ctx.config.output.filename = "server.mjs";
1065
- if (ctx.nuxt.options.sourcemap.server) {
1066
- const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1067
- ctx.config.devtool = prefix + ctx.isDev ? "cheap-module-source-map" : "source-map";
1068
- } else {
1069
- ctx.config.devtool = false;
1070
- }
1071
- ctx.config.optimization = {
1072
- splitChunks: false,
1073
- minimize: false
1074
- };
1233
+ ctx.config.output.filename = "server.mjs";
1234
+ if (ctx.nuxt.options.sourcemap.server) {
1235
+ const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1236
+ ctx.config.devtool = prefix + (ctx.isDev ? "cheap-module-source-map" : "source-map");
1237
+ } else ctx.config.devtool = false;
1238
+ ctx.config.optimization = {
1239
+ splitChunks: false,
1240
+ minimize: false
1241
+ };
1242
+ if (ctx.isDev) ctx.config.output.asyncChunks = false;
1075
1243
  }
1076
1244
  function serverStandalone(ctx) {
1077
- const inline = [
1078
- "src/",
1079
- "#app",
1080
- "nuxt",
1081
- "nuxt3",
1082
- "nuxt-nightly",
1083
- "!",
1084
- "-!",
1085
- "~",
1086
- "@/",
1087
- "#",
1088
- ...ctx.options.build.transpile
1089
- ];
1090
- const external = /* @__PURE__ */ new Set([
1091
- "nitro/runtime",
1092
- // TODO: remove in v5
1093
- "#internal/nitro",
1094
- "nitropack/runtime",
1095
- "#shared",
1096
- resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared)
1097
- ]);
1098
- if (!ctx.nuxt.options.dev) {
1099
- external.add("#internal/nuxt/paths");
1100
- external.add("#internal/nuxt/app-config");
1101
- external.add("#app-manifest");
1102
- }
1103
- if (!Array.isArray(ctx.config.externals)) {
1104
- return;
1105
- }
1106
- ctx.config.externals.push(({ request }, cb) => {
1107
- if (!request) {
1108
- return cb(void 0, false);
1109
- }
1110
- if (external.has(request)) {
1111
- return cb(void 0, true);
1112
- }
1113
- if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) {
1114
- return cb(void 0, false);
1115
- }
1116
- return cb(void 0, true);
1117
- });
1245
+ const inline = [
1246
+ "src/",
1247
+ "#app",
1248
+ "nuxt",
1249
+ "nuxt3",
1250
+ "nuxt-nightly",
1251
+ "!",
1252
+ "-!",
1253
+ "~",
1254
+ "@/",
1255
+ "#",
1256
+ ...ctx.options.build.transpile
1257
+ ];
1258
+ const external = new Set([
1259
+ "nitro/runtime",
1260
+ "#internal/nitro",
1261
+ "nitropack/runtime",
1262
+ "#shared",
1263
+ resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared),
1264
+ ...ctx.nuxt["~runtimeDependencies"] || []
1265
+ ]);
1266
+ if (!ctx.nuxt.options.dev) {
1267
+ external.add("#internal/nuxt/paths");
1268
+ external.add("#internal/nuxt/app-config");
1269
+ external.add("#app-manifest");
1270
+ }
1271
+ if (!Array.isArray(ctx.config.externals)) return;
1272
+ const conditions = [
1273
+ ctx.nuxt.options.dev ? "development" : "production",
1274
+ "node",
1275
+ "import",
1276
+ "require"
1277
+ ];
1278
+ ctx.config.externals.push(({ request, context }, cb) => {
1279
+ if (!request) return cb(void 0, false);
1280
+ if (external.has(request)) {
1281
+ const resolved = resolveModulePath(request, {
1282
+ from: context ? [context, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)) : ctx.nuxt.options.modulesDir.map((d) => directoryToURL(d)),
1283
+ suffixes: ["", "index"],
1284
+ conditions,
1285
+ try: true
1286
+ });
1287
+ if (resolved && isAbsolute(resolved)) return cb(void 0, resolved);
1288
+ return cb(void 0, true);
1289
+ }
1290
+ if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) return cb(void 0, false);
1291
+ if (context && request && !request.startsWith("node:") && (isAbsolute(context) || VIRTUAL_RE.test(context))) try {
1292
+ const resolved = resolveModulePath(resolveAlias(normalize(request), ctx.nuxt.options.alias), {
1293
+ from: [parseNodeModulePath(context).dir || ctx.nuxt.options.rootDir, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)),
1294
+ suffixes: ["", "index"],
1295
+ conditions,
1296
+ try: true
1297
+ });
1298
+ if (resolved && isAbsolute(resolved)) return cb(void 0, false);
1299
+ } catch {}
1300
+ return cb(void 0, true);
1301
+ });
1118
1302
  }
1119
1303
  function serverPlugins(ctx) {
1120
- ctx.config.plugins ||= [];
1121
- if (ctx.userConfig.serverURLPolyfill) {
1122
- ctx.config.plugins.push(new webpack.ProvidePlugin({
1123
- URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1124
- URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1125
- }));
1126
- }
1127
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1128
- ctx.config.plugins.push(new TsCheckerPlugin({
1129
- logger
1130
- }));
1131
- }
1304
+ ctx.config.plugins ||= [];
1305
+ if (ctx.userConfig.serverURLPolyfill) ctx.config.plugins.push(new webpack.ProvidePlugin({
1306
+ URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1307
+ URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1308
+ }));
1309
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1132
1310
  }
1133
-
1134
1311
  const bundle = async (nuxt) => {
1135
- const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1136
- const ctx = createWebpackConfigContext(nuxt);
1137
- ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name}`], ctx.userConfig);
1138
- await applyPresets(ctx, preset);
1139
- return ctx.config;
1140
- }));
1141
- if (!nuxt.options.dev) {
1142
- const nitro = useNitro();
1143
- nitro.hooks.hook("rollup:before", (_nitro, config) => {
1144
- const plugins = config.plugins;
1145
- const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1146
- if (existingPlugin >= 0) {
1147
- plugins.splice(existingPlugin, 1);
1148
- }
1149
- });
1150
- }
1151
- await nuxt.callHook(`${builder}:config`, webpackConfigs);
1152
- const mfs = nuxt.options.dev ? createMFS() : null;
1153
- for (const config of webpackConfigs) {
1154
- config.plugins.push(DynamicBasePlugin.webpack({
1155
- sourcemap: !!nuxt.options.sourcemap[config.name]
1156
- }));
1157
- if (config.name === "client" && nuxt.options.experimental.emitRouteChunkError && nuxt.options.builder !== "@nuxt/rspack-builder") {
1158
- config.plugins.push(new ChunkErrorPlugin());
1159
- }
1160
- }
1161
- await nuxt.callHook(`${builder}:configResolved`, webpackConfigs);
1162
- const compilers = webpackConfigs.map((config) => {
1163
- const compiler = webpack(config);
1164
- if (nuxt.options.dev && compiler) {
1165
- compiler.outputFileSystem = mfs;
1166
- }
1167
- return compiler;
1168
- });
1169
- nuxt.hook("close", async () => {
1170
- for (const compiler of compilers) {
1171
- await new Promise((resolve) => compiler?.close(resolve));
1172
- }
1173
- });
1174
- if (nuxt.options.dev) {
1175
- await Promise.all(compilers.map((c) => c && compile(c)));
1176
- return;
1177
- }
1178
- for (const c of compilers) {
1179
- if (c) {
1180
- await compile(c);
1181
- }
1182
- }
1312
+ const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1313
+ const ctx = createWebpackConfigContext(nuxt);
1314
+ ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name}`], ctx.userConfig);
1315
+ await applyPresets(ctx, preset);
1316
+ return ctx.config;
1317
+ }));
1318
+ if (!nuxt.options.dev) useNitro().hooks.hook("rollup:before", (_nitro, config) => {
1319
+ const plugins = config.plugins;
1320
+ const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1321
+ if (existingPlugin >= 0) plugins.splice(existingPlugin, 1);
1322
+ });
1323
+ await nuxt.callHook(`${builder}:config`, webpackConfigs);
1324
+ const mfs = nuxt.options.dev ? createMFS() : null;
1325
+ const ssrStylesPlugin = nuxt.options.ssr && !nuxt.options.dev && nuxt.options.features.inlineStyles ? new SSRStylesPlugin(nuxt) : null;
1326
+ for (const config of webpackConfigs) {
1327
+ config.plugins.push(DynamicBasePlugin.webpack({ sourcemap: !!nuxt.options.sourcemap[config.name] }));
1328
+ if (config.name === "client" && nuxt.options.experimental.emitRouteChunkError && nuxt.options.builder !== "@nuxt/rspack-builder") config.plugins.push(new ChunkErrorPlugin());
1329
+ if (ssrStylesPlugin) config.plugins.push(ssrStylesPlugin);
1330
+ }
1331
+ await nuxt.callHook(`${builder}:configResolved`, webpackConfigs);
1332
+ const compilers = webpackConfigs.map((config) => {
1333
+ const compiler = webpack(config);
1334
+ if (nuxt.options.dev && compiler) compiler.outputFileSystem = mfs;
1335
+ return compiler;
1336
+ });
1337
+ nuxt.hook("close", async () => {
1338
+ for (const compiler of compilers) await new Promise((resolve) => compiler.close(resolve));
1339
+ });
1340
+ if (nuxt.options.dev) {
1341
+ await Promise.all(compilers.map((c) => compile(c)));
1342
+ return;
1343
+ }
1344
+ for (const c of compilers) await compile(c);
1183
1345
  };
1184
1346
  async function createDevMiddleware(compiler) {
1185
- const nuxt = useNuxt();
1186
- logger.debug("Creating webpack middleware...");
1187
- const devMiddleware = webpackDevMiddleware(compiler, {
1188
- publicPath: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir),
1189
- outputFileSystem: compiler.outputFileSystem,
1190
- stats: "none",
1191
- ...nuxt.options.webpack.devMiddleware
1192
- });
1193
- nuxt.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1194
- const { client: _client, ...hotMiddlewareOptions } = nuxt.options.webpack.hotMiddleware || {};
1195
- const hotMiddleware = webpackHotMiddleware(compiler, {
1196
- log: false,
1197
- heartbeat: 1e4,
1198
- path: joinURL(nuxt.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1199
- ...hotMiddlewareOptions
1200
- });
1201
- const devHandler = wdmToH3Handler(devMiddleware, nuxt.options.devServer.cors);
1202
- const hotHandler = fromNodeMiddleware(hotMiddleware);
1203
- await nuxt.callHook("server:devHandler", defineEventHandler(async (event) => {
1204
- const body = await devHandler(event);
1205
- if (body !== void 0) {
1206
- return body;
1207
- }
1208
- await hotHandler(event);
1209
- }));
1210
- return devMiddleware;
1347
+ const nuxt = useNuxt();
1348
+ logger.debug("Creating webpack middleware...");
1349
+ const devMiddleware = webpackDevMiddleware(compiler, {
1350
+ publicPath: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir),
1351
+ outputFileSystem: compiler.outputFileSystem,
1352
+ stats: "none",
1353
+ ...nuxt.options.webpack.devMiddleware
1354
+ });
1355
+ nuxt.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1356
+ const { client: _client, ...hotMiddlewareOptions } = nuxt.options.webpack.hotMiddleware || {};
1357
+ const hotMiddleware = webpackHotMiddleware(compiler, {
1358
+ log: false,
1359
+ heartbeat: 1e4,
1360
+ path: joinURL(nuxt.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1361
+ ...hotMiddlewareOptions
1362
+ });
1363
+ const devHandler = wdmToH3Handler(devMiddleware);
1364
+ await nuxt.callHook("server:devHandler", defineEventHandler(async (event) => {
1365
+ const body = await devHandler(event);
1366
+ if (body !== void 0) return body;
1367
+ const { req, res } = "runtime" in event ? event.runtime.node : event.node;
1368
+ await new Promise((resolve, reject) => hotMiddleware(req, res, (err) => err ? reject(err) : resolve()));
1369
+ }), { cors: () => true });
1370
+ return devMiddleware;
1211
1371
  }
1212
- function wdmToH3Handler(devMiddleware, corsOptions) {
1213
- return defineEventHandler(async (event) => {
1214
- const isPreflight = handleCors(event, corsOptions);
1215
- if (isPreflight) {
1216
- return null;
1217
- }
1218
- if (getRequestHeader(event, "sec-fetch-mode") === "no-cors" && getRequestHeader(event, "sec-fetch-site") === "cross-site") {
1219
- throw createError({ statusCode: 403 });
1220
- }
1221
- setHeader(event, "Vary", "Origin");
1222
- event.context.webpack = {
1223
- ...event.context.webpack,
1224
- devMiddleware: devMiddleware.context
1225
- };
1226
- const { req, res } = event.node;
1227
- const body = await new Promise((resolve, reject) => {
1228
- res.stream = (stream) => {
1229
- resolve(stream);
1230
- };
1231
- res.send = (data) => {
1232
- resolve(data);
1233
- };
1234
- res.finish = (data) => {
1235
- resolve(data);
1236
- };
1237
- devMiddleware(req, res, (err) => {
1238
- if (err) {
1239
- reject(err);
1240
- } else {
1241
- resolve(void 0);
1242
- }
1243
- });
1244
- });
1245
- return body;
1246
- });
1372
+ function wdmToH3Handler(devMiddleware) {
1373
+ return defineEventHandler(async (event) => {
1374
+ const { req, res } = "runtime" in event ? event.runtime.node : event.node;
1375
+ if (req.headers["sec-fetch-mode"] === "no-cors" && req.headers["sec-fetch-site"] === "cross-site") {
1376
+ res.statusCode = 403;
1377
+ res.end("Forbidden");
1378
+ return;
1379
+ }
1380
+ event.context.webpack = {
1381
+ ...event.context.webpack,
1382
+ devMiddleware: devMiddleware.context
1383
+ };
1384
+ return await new Promise((resolve, reject) => {
1385
+ res.stream = (stream) => {
1386
+ resolve(stream);
1387
+ };
1388
+ res.send = (data) => {
1389
+ resolve(data);
1390
+ };
1391
+ res.finish = (data) => {
1392
+ resolve(data);
1393
+ };
1394
+ devMiddleware(req, res, (err) => {
1395
+ if (err) reject(err);
1396
+ else resolve(void 0);
1397
+ });
1398
+ });
1399
+ });
1247
1400
  }
1248
1401
  async function compile(compiler) {
1249
- const nuxt = useNuxt();
1250
- await nuxt.callHook(`${builder}:compile`, { name: compiler.options.name, compiler });
1251
- compiler.hooks.done.tap("load-resources", async (stats2) => {
1252
- await nuxt.callHook(`${builder}:compiled`, { name: compiler.options.name, compiler, stats: stats2 });
1253
- });
1254
- if (nuxt.options.dev) {
1255
- const compilersWatching = [];
1256
- nuxt.hook("close", async () => {
1257
- await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1258
- });
1259
- if (compiler.options.name === "client") {
1260
- return new Promise((resolve, reject) => {
1261
- compiler.hooks.done.tap("nuxt-dev", () => {
1262
- resolve(null);
1263
- });
1264
- compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1265
- reject(err);
1266
- });
1267
- createDevMiddleware(compiler).then((devMiddleware) => {
1268
- if (devMiddleware.context.watching) {
1269
- compilersWatching.push(devMiddleware.context.watching);
1270
- }
1271
- });
1272
- });
1273
- }
1274
- return new Promise((resolve, reject) => {
1275
- const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1276
- if (err) {
1277
- return reject(err);
1278
- }
1279
- resolve(null);
1280
- });
1281
- compilersWatching.push(watching);
1282
- });
1283
- }
1284
- const stats = await new Promise((resolve, reject) => compiler.run((err, stats2) => err ? reject(err) : resolve(stats2)));
1285
- if (stats.hasErrors()) {
1286
- const error = new Error("Nuxt build error");
1287
- error.stack = stats.toString("errors-only");
1288
- throw error;
1289
- }
1402
+ const nuxt = useNuxt();
1403
+ await nuxt.callHook(`${builder}:compile`, {
1404
+ name: compiler.options.name,
1405
+ compiler
1406
+ });
1407
+ compiler.hooks.done.tap("load-resources", async (stats) => {
1408
+ await nuxt.callHook(`${builder}:compiled`, {
1409
+ name: compiler.options.name,
1410
+ compiler,
1411
+ stats
1412
+ });
1413
+ });
1414
+ if (nuxt.options.dev) {
1415
+ const compilersWatching = [];
1416
+ nuxt.hook("close", async () => {
1417
+ await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1418
+ });
1419
+ if (compiler.options.name === "client") return new Promise((resolve, reject) => {
1420
+ compiler.hooks.done.tap("nuxt-dev", () => {
1421
+ resolve(null);
1422
+ });
1423
+ compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1424
+ reject(err);
1425
+ });
1426
+ createDevMiddleware(compiler).then((devMiddleware) => {
1427
+ if (devMiddleware.context.watching) compilersWatching.push(devMiddleware.context.watching);
1428
+ });
1429
+ });
1430
+ return new Promise((resolve, reject) => {
1431
+ const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1432
+ if (err) return reject(err);
1433
+ resolve(null);
1434
+ });
1435
+ compilersWatching.push(watching);
1436
+ });
1437
+ }
1438
+ const stats = await new Promise((resolve, reject) => compiler.run((err, stats) => err ? reject(err) : resolve(stats)));
1439
+ if (stats.hasErrors()) {
1440
+ const error = /* @__PURE__ */ new Error("Nuxt build error");
1441
+ error.stack = stats.toString("errors-only");
1442
+ throw error;
1443
+ }
1444
+ }
1445
+ function defineEventHandler(handler) {
1446
+ return Object.assign(handler, { __is_handler__: true });
1290
1447
  }
1291
-
1292
1448
  export { bundle };