@nuxt/webpack-builder 4.0.0-0 → 4.0.0-alpha.2

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.
Files changed (2) hide show
  1. package/dist/index.mjs +152 -135
  2. package/package.json +12 -12
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
1
  import pify from 'pify';
2
- import { join, resolve, normalize, dirname, isAbsolute } from 'pathe';
3
2
  import { fromNodeMiddleware, defineEventHandler, handleCors, getRequestHeader, createError, setHeader } from 'h3';
4
3
  import webpackDevMiddleware from 'webpack-dev-middleware';
5
4
  import webpackHotMiddleware from 'webpack-hot-middleware';
6
5
  import { defu } from 'defu';
7
6
  import { joinURL } from 'ufo';
8
- import { logger, importModule, useNitro, useNuxt } from '@nuxt/kit';
7
+ import { logger, useNitro, useNuxt } from '@nuxt/kit';
9
8
  import { createUnplugin } from 'unplugin';
10
9
  import MagicString from 'magic-string';
11
10
  import { webpack, WebpackBarPlugin, builder, MiniCssExtractPlugin, TsCheckerPlugin } from '#builder';
11
+ import { join, resolve, basename, normalize, dirname, isAbsolute } from 'pathe';
12
12
  import { createFsFromVolume, Volume } from 'memfs';
13
13
  import querystring from 'node:querystring';
14
14
  import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
@@ -17,6 +17,7 @@ import TimeFixPlugin from 'time-fix-plugin';
17
17
  import FriendlyErrorsWebpackPlugin from '@nuxt/friendly-errors-webpack-plugin';
18
18
  import escapeRegExp from 'escape-string-regexp';
19
19
  import { isTest } from 'std-env';
20
+ import { genObjectFromRawEntries, genString } from 'knitwork';
20
21
  import { EsbuildPlugin } from 'esbuild-loader';
21
22
  import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
22
23
  import createResolver from 'postcss-import-resolver';
@@ -25,8 +26,6 @@ import VueLoaderPlugin from 'vue-loader/dist/pluginWebpack5.js';
25
26
  import { mkdir, writeFile } from 'node:fs/promises';
26
27
  import { normalizeWebpackManifest } from 'vue-bundle-renderer';
27
28
  import { hash } from 'ohash';
28
- import { glob } from 'tinyglobby';
29
- import { genSafeVariableName } from 'knitwork';
30
29
 
31
30
  const defaults = {
32
31
  globalPublicPath: "__webpack_public_path__",
@@ -179,6 +178,123 @@ class WarningIgnorePlugin {
179
178
  }
180
179
  }
181
180
 
181
+ const validate = (compiler) => {
182
+ if (compiler.options.target !== "node") {
183
+ logger.warn('webpack config `target` should be "node".');
184
+ }
185
+ if (!compiler.options.externals) {
186
+ logger.info(
187
+ "It is recommended to externalize dependencies in the server build for better build performance."
188
+ );
189
+ }
190
+ };
191
+ const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
192
+ const isJS = (file) => isJSRegExp.test(file);
193
+ const extractQueryPartJS = (file) => isJSRegExp.exec(file)?.[1];
194
+ const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
195
+ const isCSS = (file) => isCSSRegExp.test(file);
196
+ const isHotUpdate = (file) => file.includes("hot-update");
197
+
198
+ const DYNAMIC_IMPORT_RE = /import\([^)]*\+\s*__webpack_require__[^+]*\)\.then/;
199
+ const DYNAMIC_IMPORT_REPLACE_RE = /import\([^)]*\+\s*(__webpack_require__[^+]*)\)\.then/g;
200
+ const HELPER_FILENAME = "_dynamic-import-helper.mjs";
201
+ const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";
202
+ `;
203
+ class RollupCompatDynamicImportPlugin {
204
+ apply(compiler) {
205
+ compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
206
+ compilation.hooks.processAssets.tapAsync(
207
+ {
208
+ name: "RollupCompatDynamicImportPlugin",
209
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
210
+ },
211
+ (assets, callback) => {
212
+ try {
213
+ const targetFiles = /* @__PURE__ */ new Set();
214
+ for (const chunk of compilation.chunks) {
215
+ if (chunk.canBeInitial() || chunk.hasRuntime()) {
216
+ for (const file of chunk.files || []) {
217
+ targetFiles.add(file);
218
+ }
219
+ }
220
+ }
221
+ for (const [filename, asset] of Object.entries(assets)) {
222
+ if (!isJS(filename)) {
223
+ continue;
224
+ }
225
+ if (!targetFiles.has(filename)) {
226
+ continue;
227
+ }
228
+ const source = asset.source();
229
+ const originalCode = typeof source === "string" ? source : source.toString();
230
+ if (!DYNAMIC_IMPORT_RE.test(originalCode)) {
231
+ continue;
232
+ }
233
+ const transformedCode = this.transformDynamicImports(originalCode);
234
+ if (transformedCode !== originalCode) {
235
+ assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
236
+ }
237
+ }
238
+ this.generateDynamicImportHelper(compilation);
239
+ callback();
240
+ } catch (error) {
241
+ callback(error);
242
+ }
243
+ }
244
+ );
245
+ });
246
+ }
247
+ transformDynamicImports(source) {
248
+ let transformed = source;
249
+ let needsHelperImport = false;
250
+ transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
251
+ needsHelperImport = true;
252
+ return `_rollupDynamicImport(${filename}).then`;
253
+ });
254
+ if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) {
255
+ transformed = HELPER_IMPORT + transformed;
256
+ }
257
+ return transformed;
258
+ }
259
+ generateDynamicImportHelper(compilation) {
260
+ const chunkFiles = [];
261
+ for (const chunk of compilation.chunks) {
262
+ if (chunk.hasRuntime()) {
263
+ continue;
264
+ }
265
+ for (const filename of chunk.files) {
266
+ if (filename && isJS(filename)) {
267
+ chunkFiles.push(filename);
268
+ }
269
+ }
270
+ }
271
+ if (chunkFiles.length === 0) {
272
+ return;
273
+ }
274
+ const helperContent = this.generateHelperContent(chunkFiles);
275
+ compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
276
+ }
277
+ generateHelperContent(chunkFiles) {
278
+ return `
279
+ // Rollup-compatible dynamic import helper generated by webpack
280
+ // This helper enables rollup to consume webpack chunks directly
281
+
282
+ const chunkMap = ${genObjectFromRawEntries(chunkFiles.map((filename) => [filename, `() => import(${genString("./" + filename)})`]))}
283
+
284
+ // Dynamic import function that rollup can understand
285
+ export function _rollupDynamicImport(chunkId) {
286
+ const chunk = chunkMap[chunkId]
287
+ if (!chunk) {
288
+ return Promise.reject(new Error(\`Chunk \${chunkId} not found in chunkMap. Available chunks: \${Object.keys(chunkMap).join(', ')}\`))
289
+ }
290
+
291
+ // Use actual dynamic import for the chunk
292
+ return chunk()
293
+ }
294
+ `;
295
+ }
296
+ }
297
+
182
298
  async function base(ctx) {
183
299
  await applyPresets(ctx, [
184
300
  baseAlias,
@@ -267,15 +383,21 @@ function basePlugins(ctx) {
267
383
  }
268
384
  }));
269
385
  }
386
+ if (ctx.isServer && !ctx.isDev) {
387
+ ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
388
+ }
270
389
  }
271
390
  function baseAlias(ctx) {
272
391
  ctx.alias = {
273
392
  "#app": ctx.options.appDir,
393
+ [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
274
394
  ...ctx.options.alias,
275
395
  ...ctx.alias
276
396
  };
277
397
  if (ctx.isClient) {
278
398
  ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
399
+ ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
400
+ ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
279
401
  }
280
402
  }
281
403
  function baseResolve(ctx) {
@@ -580,23 +702,6 @@ async function createPostcssLoadersRule(ctx) {
580
702
  };
581
703
  }
582
704
 
583
- const validate = (compiler) => {
584
- if (compiler.options.target !== "node") {
585
- logger.warn('webpack config `target` should be "node".');
586
- }
587
- if (!compiler.options.externals) {
588
- logger.info(
589
- "It is recommended to externalize dependencies in the server build for better build performance."
590
- );
591
- }
592
- };
593
- const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
594
- const isJS = (file) => isJSRegExp.test(file);
595
- const extractQueryPartJS = (file) => isJSRegExp.exec(file)?.[1];
596
- const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
597
- const isCSS = (file) => isCSSRegExp.test(file);
598
- const isHotUpdate = (file) => file.includes("hot-update");
599
-
600
705
  class VueSSRClientPlugin {
601
706
  options;
602
707
  constructor(options) {
@@ -967,13 +1072,18 @@ function serverStandalone(ctx) {
967
1072
  "#",
968
1073
  ...ctx.options.build.transpile
969
1074
  ];
970
- const external = [
1075
+ const external = /* @__PURE__ */ new Set([
971
1076
  "nitro/runtime",
1077
+ // TODO: remove in v5
1078
+ "#internal/nitro",
1079
+ "nitropack/runtime",
972
1080
  "#shared",
973
1081
  resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared)
974
- ];
1082
+ ]);
975
1083
  if (!ctx.nuxt.options.dev) {
976
- external.push("#internal/nuxt/paths", "#internal/nuxt/app-config", "#app-manifest");
1084
+ external.add("#internal/nuxt/paths");
1085
+ external.add("#internal/nuxt/app-config");
1086
+ external.add("#app-manifest");
977
1087
  }
978
1088
  if (!Array.isArray(ctx.config.externals)) {
979
1089
  return;
@@ -982,7 +1092,7 @@ function serverStandalone(ctx) {
982
1092
  if (!request) {
983
1093
  return cb(void 0, false);
984
1094
  }
985
- if (external.includes(request)) {
1095
+ if (external.has(request)) {
986
1096
  return cb(void 0, true);
987
1097
  }
988
1098
  if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) {
@@ -1006,91 +1116,6 @@ function serverPlugins(ctx) {
1006
1116
  }
1007
1117
  }
1008
1118
 
1009
- const PLUGIN_NAME = "dynamic-require";
1010
- const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.mjs`;
1011
- const DYNAMIC_REQUIRE_RE = /import\((?:.*\+\s*)?"\.\/" ?\+(.*)\).then/g;
1012
- const BACKWARD_SLASH_RE = /\\/g;
1013
- function dynamicRequire({ dir, ignore, inline }) {
1014
- return {
1015
- name: PLUGIN_NAME,
1016
- transform(code, _id) {
1017
- return {
1018
- code: code.replace(
1019
- DYNAMIC_REQUIRE_RE,
1020
- `import('${HELPER_DYNAMIC}').then(r => r.default || r).then(dynamicRequire => dynamicRequire($1)).then`
1021
- ),
1022
- map: null
1023
- };
1024
- },
1025
- resolveId(id) {
1026
- return id === HELPER_DYNAMIC ? id : null;
1027
- },
1028
- // TODO: Async chunk loading over network!
1029
- // renderDynamicImport () {
1030
- // return {
1031
- // left: 'fetch(', right: ')'
1032
- // }
1033
- // },
1034
- async load(_id) {
1035
- if (_id !== HELPER_DYNAMIC) {
1036
- return null;
1037
- }
1038
- let files = [];
1039
- try {
1040
- const wpManifest = resolve(dir, "./server.manifest.json");
1041
- files = await importModule(wpManifest).then((r) => Object.keys(r.files).filter((file) => !ignore.includes(file)));
1042
- } catch {
1043
- files = await glob("**/*.{cjs,mjs,js}", {
1044
- cwd: dir,
1045
- absolute: false,
1046
- ignore
1047
- });
1048
- }
1049
- const chunks = (await Promise.all(
1050
- files.map(async (id) => ({
1051
- id,
1052
- src: resolve(dir, id).replace(BACKWARD_SLASH_RE, "/"),
1053
- name: genSafeVariableName(id),
1054
- meta: await getWebpackChunkMeta(resolve(dir, id))
1055
- }))
1056
- )).filter((chunk) => chunk.meta);
1057
- return inline ? TMPL_INLINE({ chunks }) : TMPL_LAZY({ chunks });
1058
- }
1059
- };
1060
- }
1061
- async function getWebpackChunkMeta(src) {
1062
- const chunk = await importModule(src) || {};
1063
- const { __webpack_id__, __webpack_ids__, __webpack_modules__, id = __webpack_id__, ids = __webpack_ids__, modules = __webpack_modules__ } = chunk;
1064
- if (!id && !ids) {
1065
- return null;
1066
- }
1067
- return {
1068
- id,
1069
- ids,
1070
- moduleIds: Object.keys(modules || {})
1071
- };
1072
- }
1073
- function TMPL_INLINE({ chunks }) {
1074
- return `${chunks.map((i) => `import * as ${i.name} from '${i.src}'`).join("\n")}
1075
- const dynamicChunks = {
1076
- ${chunks.map((i) => ` ['${i.id}']: ${i.name}`).join(",\n")}
1077
- };
1078
-
1079
- export default function dynamicRequire(id) {
1080
- return Promise.resolve(dynamicChunks[id]);
1081
- };`;
1082
- }
1083
- function TMPL_LAZY({ chunks }) {
1084
- return `
1085
- const dynamicChunks = {
1086
- ${chunks.map((i) => ` ['${i.id}']: () => import('${i.src}')`).join(",\n")}
1087
- };
1088
-
1089
- export default function dynamicRequire(id) {
1090
- return dynamicChunks[id]();
1091
- };`;
1092
- }
1093
-
1094
1119
  const bundle = async (nuxt) => {
1095
1120
  const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1096
1121
  const ctx = createWebpackConfigContext(nuxt);
@@ -1100,21 +1125,13 @@ const bundle = async (nuxt) => {
1100
1125
  }));
1101
1126
  if (!nuxt.options.dev) {
1102
1127
  const nitro = useNitro();
1103
- const dynamicRequirePlugin = dynamicRequire({
1104
- dir: resolve(nuxt.options.buildDir, "dist/server"),
1105
- inline: nitro.options.node === false || nitro.options.inlineDynamicImports,
1106
- ignore: [
1107
- "client.manifest.mjs",
1108
- "server.js",
1109
- "server.cjs",
1110
- "server.mjs",
1111
- "server.manifest.mjs"
1112
- ]
1128
+ nitro.hooks.hook("rollup:before", (_nitro, config) => {
1129
+ const plugins = config.plugins;
1130
+ const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1131
+ if (existingPlugin >= 0) {
1132
+ plugins.splice(existingPlugin, 1);
1133
+ }
1113
1134
  });
1114
- const prerenderRollupPlugins = nitro.options._config.rollupConfig.plugins;
1115
- const rollupPlugins = nitro.options.rollupConfig.plugins;
1116
- prerenderRollupPlugins.push(dynamicRequirePlugin);
1117
- rollupPlugins.push(dynamicRequirePlugin);
1118
1135
  }
1119
1136
  await nuxt.callHook(`${builder}:config`, webpackConfigs);
1120
1137
  const mfs = nuxt.options.dev ? createMFS() : null;
@@ -1136,7 +1153,7 @@ const bundle = async (nuxt) => {
1136
1153
  });
1137
1154
  nuxt.hook("close", async () => {
1138
1155
  for (const compiler of compilers) {
1139
- await new Promise((resolve2) => compiler.close(resolve2));
1156
+ await new Promise((resolve) => compiler.close(resolve));
1140
1157
  }
1141
1158
  });
1142
1159
  if (nuxt.options.dev) {
@@ -1190,21 +1207,21 @@ function wdmToH3Handler(devMiddleware, corsOptions) {
1190
1207
  devMiddleware: devMiddleware.context
1191
1208
  };
1192
1209
  const { req, res } = event.node;
1193
- const body = await new Promise((resolve2, reject) => {
1210
+ const body = await new Promise((resolve, reject) => {
1194
1211
  res.stream = (stream) => {
1195
- resolve2(stream);
1212
+ resolve(stream);
1196
1213
  };
1197
1214
  res.send = (data) => {
1198
- resolve2(data);
1215
+ resolve(data);
1199
1216
  };
1200
1217
  res.finish = (data) => {
1201
- resolve2(data);
1218
+ resolve(data);
1202
1219
  };
1203
1220
  devMiddleware(req, res, (err) => {
1204
1221
  if (err) {
1205
1222
  reject(err);
1206
1223
  } else {
1207
- resolve2(void 0);
1224
+ resolve(void 0);
1208
1225
  }
1209
1226
  });
1210
1227
  });
@@ -1223,9 +1240,9 @@ async function compile(compiler) {
1223
1240
  await Promise.all(compilersWatching.map((watching) => pify(watching.close.bind(watching))()));
1224
1241
  });
1225
1242
  if (compiler.options.name === "client") {
1226
- return new Promise((resolve2, reject) => {
1243
+ return new Promise((resolve, reject) => {
1227
1244
  compiler.hooks.done.tap("nuxt-dev", () => {
1228
- resolve2(null);
1245
+ resolve(null);
1229
1246
  });
1230
1247
  compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1231
1248
  reject(err);
@@ -1237,17 +1254,17 @@ async function compile(compiler) {
1237
1254
  });
1238
1255
  });
1239
1256
  }
1240
- return new Promise((resolve2, reject) => {
1257
+ return new Promise((resolve, reject) => {
1241
1258
  const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1242
1259
  if (err) {
1243
1260
  return reject(err);
1244
1261
  }
1245
- resolve2(null);
1262
+ resolve(null);
1246
1263
  });
1247
1264
  compilersWatching.push(watching);
1248
1265
  });
1249
1266
  }
1250
- const stats = await new Promise((resolve2, reject) => compiler.run((err, stats2) => err ? reject(err) : resolve2(stats2)));
1267
+ const stats = await new Promise((resolve, reject) => compiler.run((err, stats2) => err ? reject(err) : resolve(stats2)));
1251
1268
  if (stats.hasErrors()) {
1252
1269
  const error = new Error("Nuxt build error");
1253
1270
  error.stack = stats.toString("errors-only");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/webpack-builder",
3
- "version": "4.0.0-0",
3
+ "version": "4.0.0-alpha.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",
@@ -40,12 +40,12 @@
40
40
  "jiti": "^2.4.2",
41
41
  "knitwork": "^1.2.0",
42
42
  "magic-string": "^0.30.17",
43
- "memfs": "^4.17.1",
43
+ "memfs": "^4.17.2",
44
44
  "mini-css-extract-plugin": "^2.9.2",
45
45
  "ohash": "^2.0.11",
46
46
  "pathe": "^2.0.3",
47
47
  "pify": "^6.1.0",
48
- "postcss": "^8.5.3",
48
+ "postcss": "^8.5.4",
49
49
  "postcss-import": "^16.1.0",
50
50
  "postcss-import-resolver": "^2.0.0",
51
51
  "postcss-loader": "^8.1.1",
@@ -53,28 +53,28 @@
53
53
  "pug-plain-loader": "^1.1.0",
54
54
  "std-env": "^3.9.0",
55
55
  "time-fix-plugin": "^2.0.7",
56
- "tinyglobby": "^0.2.13",
56
+ "tinyglobby": "^0.2.14",
57
57
  "ufo": "^1.6.1",
58
- "unenv": "^2.0.0-rc.15",
59
- "unplugin": "^2.3.3",
58
+ "unenv": "^2.0.0-rc.17",
59
+ "unplugin": "^2.3.5",
60
60
  "url-loader": "^4.1.1",
61
61
  "vue-bundle-renderer": "^2.1.1",
62
62
  "vue-loader": "^17.4.2",
63
- "webpack": "^5.99.8",
63
+ "webpack": "^5.99.9",
64
64
  "webpack-bundle-analyzer": "^4.10.2",
65
65
  "webpack-dev-middleware": "^7.4.2",
66
66
  "webpack-hot-middleware": "^2.26.1",
67
67
  "webpackbar": "^7.0.0",
68
- "@nuxt/kit": "4.0.0-0"
68
+ "@nuxt/kit": "4.0.0-alpha.2"
69
69
  },
70
70
  "devDependencies": {
71
- "@rspack/core": "1.3.9",
71
+ "@rspack/core": "1.3.15",
72
72
  "@types/webpack-bundle-analyzer": "4.7.0",
73
73
  "@types/webpack-hot-middleware": "2.25.9",
74
- "rollup": "4.40.2",
74
+ "rollup": "4.42.0",
75
75
  "unbuild": "3.5.0",
76
- "vue": "3.5.13",
77
- "@nuxt/schema": "4.0.0-0"
76
+ "vue": "3.5.16",
77
+ "@nuxt/schema": "4.0.0-alpha.2"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "vue": "^3.3.4"