@nuxt/webpack-builder 4.0.0-alpha.1 → 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 +137 -134
  2. package/package.json +6 -6
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
1
  import pify from 'pify';
2
- import { join, resolve, basename, 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,6 +383,9 @@ 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 = {
@@ -583,23 +702,6 @@ async function createPostcssLoadersRule(ctx) {
583
702
  };
584
703
  }
585
704
 
586
- const validate = (compiler) => {
587
- if (compiler.options.target !== "node") {
588
- logger.warn('webpack config `target` should be "node".');
589
- }
590
- if (!compiler.options.externals) {
591
- logger.info(
592
- "It is recommended to externalize dependencies in the server build for better build performance."
593
- );
594
- }
595
- };
596
- const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
597
- const isJS = (file) => isJSRegExp.test(file);
598
- const extractQueryPartJS = (file) => isJSRegExp.exec(file)?.[1];
599
- const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
600
- const isCSS = (file) => isCSSRegExp.test(file);
601
- const isHotUpdate = (file) => file.includes("hot-update");
602
-
603
705
  class VueSSRClientPlugin {
604
706
  options;
605
707
  constructor(options) {
@@ -1014,92 +1116,6 @@ function serverPlugins(ctx) {
1014
1116
  }
1015
1117
  }
1016
1118
 
1017
- const PLUGIN_NAME = "dynamic-require";
1018
- const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.mjs`;
1019
- const DYNAMIC_REQUIRE_RE = /import\((?:.*\+\s*)?"\.\/" ?\+(.*)\).then/g;
1020
- const BACKWARD_SLASH_RE = /\\/g;
1021
- function dynamicRequire({ dir, ignore, inline }) {
1022
- const filesToIgnore = new Set(ignore);
1023
- return {
1024
- name: PLUGIN_NAME,
1025
- transform(code, _id) {
1026
- return {
1027
- code: code.replace(
1028
- DYNAMIC_REQUIRE_RE,
1029
- `import('${HELPER_DYNAMIC}').then(r => r.default || r).then(dynamicRequire => dynamicRequire($1)).then`
1030
- ),
1031
- map: null
1032
- };
1033
- },
1034
- resolveId(id) {
1035
- return id === HELPER_DYNAMIC ? id : null;
1036
- },
1037
- // TODO: Async chunk loading over network!
1038
- // renderDynamicImport () {
1039
- // return {
1040
- // left: 'fetch(', right: ')'
1041
- // }
1042
- // },
1043
- async load(_id) {
1044
- if (_id !== HELPER_DYNAMIC) {
1045
- return null;
1046
- }
1047
- let files = [];
1048
- try {
1049
- const wpManifest = resolve(dir, "./server.manifest.json");
1050
- files = await importModule(wpManifest).then((r) => Object.keys(r.files).filter((file) => !filesToIgnore.has(file)));
1051
- } catch {
1052
- files = await glob("**/*.{cjs,mjs,js}", {
1053
- cwd: dir,
1054
- absolute: false,
1055
- ignore
1056
- });
1057
- }
1058
- const chunks = (await Promise.all(
1059
- files.map(async (id) => ({
1060
- id,
1061
- src: resolve(dir, id).replace(BACKWARD_SLASH_RE, "/"),
1062
- name: genSafeVariableName(id),
1063
- meta: await getWebpackChunkMeta(resolve(dir, id))
1064
- }))
1065
- )).filter((chunk) => chunk.meta);
1066
- return inline ? TMPL_INLINE({ chunks }) : TMPL_LAZY({ chunks });
1067
- }
1068
- };
1069
- }
1070
- async function getWebpackChunkMeta(src) {
1071
- const chunk = await importModule(src) || {};
1072
- const { __webpack_id__, __webpack_ids__, __webpack_modules__, id = __webpack_id__, ids = __webpack_ids__, modules = __webpack_modules__ } = chunk;
1073
- if (!id && !ids) {
1074
- return null;
1075
- }
1076
- return {
1077
- id,
1078
- ids,
1079
- moduleIds: Object.keys(modules || {})
1080
- };
1081
- }
1082
- function TMPL_INLINE({ chunks }) {
1083
- return `${chunks.map((i) => `import * as ${i.name} from '${i.src}'`).join("\n")}
1084
- const dynamicChunks = {
1085
- ${chunks.map((i) => ` ['${i.id}']: ${i.name}`).join(",\n")}
1086
- };
1087
-
1088
- export default function dynamicRequire(id) {
1089
- return Promise.resolve(dynamicChunks[id]);
1090
- };`;
1091
- }
1092
- function TMPL_LAZY({ chunks }) {
1093
- return `
1094
- const dynamicChunks = {
1095
- ${chunks.map((i) => ` ['${i.id}']: () => import('${i.src}')`).join(",\n")}
1096
- };
1097
-
1098
- export default function dynamicRequire(id) {
1099
- return dynamicChunks[id]();
1100
- };`;
1101
- }
1102
-
1103
1119
  const bundle = async (nuxt) => {
1104
1120
  const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1105
1121
  const ctx = createWebpackConfigContext(nuxt);
@@ -1109,26 +1125,13 @@ const bundle = async (nuxt) => {
1109
1125
  }));
1110
1126
  if (!nuxt.options.dev) {
1111
1127
  const nitro = useNitro();
1112
- const dynamicRequirePlugin = dynamicRequire({
1113
- dir: resolve(nuxt.options.buildDir, "dist/server"),
1114
- inline: nitro.options.node === false || nitro.options.inlineDynamicImports,
1115
- ignore: [
1116
- "client.manifest.mjs",
1117
- "server.js",
1118
- "server.cjs",
1119
- "server.mjs",
1120
- "server.manifest.mjs"
1121
- ]
1122
- });
1123
- const prerenderRollupPlugins = nitro.options._config.rollupConfig.plugins;
1124
- const rollupPlugins = nitro.options.rollupConfig.plugins;
1125
- for (const plugins of [prerenderRollupPlugins, rollupPlugins]) {
1128
+ nitro.hooks.hook("rollup:before", (_nitro, config) => {
1129
+ const plugins = config.plugins;
1126
1130
  const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1127
1131
  if (existingPlugin >= 0) {
1128
1132
  plugins.splice(existingPlugin, 1);
1129
1133
  }
1130
- plugins.push(dynamicRequirePlugin);
1131
- }
1134
+ });
1132
1135
  }
1133
1136
  await nuxt.callHook(`${builder}:config`, webpackConfigs);
1134
1137
  const mfs = nuxt.options.dev ? createMFS() : null;
@@ -1150,7 +1153,7 @@ const bundle = async (nuxt) => {
1150
1153
  });
1151
1154
  nuxt.hook("close", async () => {
1152
1155
  for (const compiler of compilers) {
1153
- await new Promise((resolve2) => compiler.close(resolve2));
1156
+ await new Promise((resolve) => compiler.close(resolve));
1154
1157
  }
1155
1158
  });
1156
1159
  if (nuxt.options.dev) {
@@ -1204,21 +1207,21 @@ function wdmToH3Handler(devMiddleware, corsOptions) {
1204
1207
  devMiddleware: devMiddleware.context
1205
1208
  };
1206
1209
  const { req, res } = event.node;
1207
- const body = await new Promise((resolve2, reject) => {
1210
+ const body = await new Promise((resolve, reject) => {
1208
1211
  res.stream = (stream) => {
1209
- resolve2(stream);
1212
+ resolve(stream);
1210
1213
  };
1211
1214
  res.send = (data) => {
1212
- resolve2(data);
1215
+ resolve(data);
1213
1216
  };
1214
1217
  res.finish = (data) => {
1215
- resolve2(data);
1218
+ resolve(data);
1216
1219
  };
1217
1220
  devMiddleware(req, res, (err) => {
1218
1221
  if (err) {
1219
1222
  reject(err);
1220
1223
  } else {
1221
- resolve2(void 0);
1224
+ resolve(void 0);
1222
1225
  }
1223
1226
  });
1224
1227
  });
@@ -1237,9 +1240,9 @@ async function compile(compiler) {
1237
1240
  await Promise.all(compilersWatching.map((watching) => pify(watching.close.bind(watching))()));
1238
1241
  });
1239
1242
  if (compiler.options.name === "client") {
1240
- return new Promise((resolve2, reject) => {
1243
+ return new Promise((resolve, reject) => {
1241
1244
  compiler.hooks.done.tap("nuxt-dev", () => {
1242
- resolve2(null);
1245
+ resolve(null);
1243
1246
  });
1244
1247
  compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1245
1248
  reject(err);
@@ -1251,17 +1254,17 @@ async function compile(compiler) {
1251
1254
  });
1252
1255
  });
1253
1256
  }
1254
- return new Promise((resolve2, reject) => {
1257
+ return new Promise((resolve, reject) => {
1255
1258
  const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1256
1259
  if (err) {
1257
1260
  return reject(err);
1258
1261
  }
1259
- resolve2(null);
1262
+ resolve(null);
1260
1263
  });
1261
1264
  compilersWatching.push(watching);
1262
1265
  });
1263
1266
  }
1264
- 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)));
1265
1268
  if (stats.hasErrors()) {
1266
1269
  const error = new Error("Nuxt build error");
1267
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-alpha.1",
3
+ "version": "4.0.0-alpha.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",
@@ -60,21 +60,21 @@
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-alpha.1"
68
+ "@nuxt/kit": "4.0.0-alpha.2"
69
69
  },
70
70
  "devDependencies": {
71
- "@rspack/core": "1.3.13",
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.41.1",
74
+ "rollup": "4.42.0",
75
75
  "unbuild": "3.5.0",
76
76
  "vue": "3.5.16",
77
- "@nuxt/schema": "4.0.0-alpha.1"
77
+ "@nuxt/schema": "4.0.0-alpha.2"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "vue": "^3.3.4"