@vizejs/vite-plugin 0.153.0 → 0.155.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +71 -22
  2. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -94,6 +94,12 @@ function hasDelegatedStyles(compiled) {
94
94
  function supportsTemplateOnlyHmr(output) {
95
95
  return /(?:^|\n)(?:_sfc_main|__sfc__)\.render\s*=\s*render\b/m.test(output);
96
96
  }
97
+ function insertAfterStaticImports(output, imports) {
98
+ let insertAt = 0;
99
+ for (const match of output.matchAll(/^import\b[^\n]*(?:\r?\n|$)/gm)) insertAt = (match.index ?? 0) + match[0].length;
100
+ if (insertAt === 0) return `${imports}\n${output}`;
101
+ return `${output.slice(0, insertAt)}${imports}\n${output.slice(insertAt)}`;
102
+ }
97
103
  function generateScopeId(filename) {
98
104
  return createHash("sha256").update(filename).digest("hex").slice(0, 8);
99
105
  }
@@ -153,7 +159,7 @@ function generateOutput(compiled, options) {
153
159
  }
154
160
  }
155
161
  const allImports = [...styleImports, ...cssModuleImports].join("\n");
156
- if (allImports) output = allImports + "\n" + output;
162
+ if (allImports) output = insertAfterStaticImports(output, allImports);
157
163
  if (cssModuleImports.length > 0) {
158
164
  const moduleBindings = [];
159
165
  for (const block of compiled.styles) if (isCssModule(block)) {
@@ -388,10 +394,13 @@ function getCompileOptionsForRequest(state, ssr) {
388
394
  };
389
395
  }
390
396
  function syncCollectedCssForFile(state, filePath, compiled) {
391
- if (!compiled || !state.isProduction) return;
397
+ if (!compiled || !state.extractCss) return;
392
398
  if (compiled.css && !hasDelegatedStyles(compiled)) state.collectedCss.set(filePath, resolveCssImports(compiled.css, filePath, state.cssAliasRules, false));
393
399
  else state.collectedCss.delete(filePath);
394
400
  }
401
+ function shouldExtractCssForRequest(state, ssr) {
402
+ return state.isProduction && !ssr;
403
+ }
395
404
  function clearBuildCaches(state) {
396
405
  state.cache.clear();
397
406
  state.ssrCache.clear();
@@ -424,7 +433,7 @@ async function compileAll(state) {
424
433
  for (const file of deletedFiles) {
425
434
  state.cache.delete(file);
426
435
  state.ssrCache.delete(file);
427
- state.collectedCss.delete(file);
436
+ if (state.extractCss) state.collectedCss.delete(file);
428
437
  state.precompileMetadata.delete(file);
429
438
  state.pendingHmrUpdateTypes.delete(file);
430
439
  }
@@ -435,7 +444,7 @@ async function compileAll(state) {
435
444
  return;
436
445
  }
437
446
  for (const file of changedFiles) {
438
- state.collectedCss.delete(file);
447
+ if (state.extractCss) state.collectedCss.delete(file);
439
448
  state.pendingHmrUpdateTypes.delete(file);
440
449
  }
441
450
  let successCount = 0;
@@ -454,7 +463,7 @@ async function compileAll(state) {
454
463
  } catch (e) {
455
464
  failedCount++;
456
465
  state.cache.delete(file);
457
- state.collectedCss.delete(file);
466
+ if (state.extractCss) state.collectedCss.delete(file);
458
467
  state.precompileMetadata.delete(file);
459
468
  precompileFailures.push(`[vize] Failed to read ${file}: ${formatUnknownError$1(e)}`);
460
469
  state.logger.error(`Failed to read ${file}:`, e);
@@ -474,7 +483,7 @@ async function compileAll(state) {
474
483
  const metadata = currentMetadata.get(fileResult.path);
475
484
  if (fileResult.errors.length > 0) {
476
485
  state.cache.delete(fileResult.path);
477
- state.collectedCss.delete(fileResult.path);
486
+ if (state.extractCss) state.collectedCss.delete(fileResult.path);
478
487
  state.precompileMetadata.delete(fileResult.path);
479
488
  precompileFailures.push(formatCompileErrorMessage(fileResult.path, fileResult.errors));
480
489
  continue;
@@ -884,13 +893,17 @@ function normalizeVueServerRendererImport(code) {
884
893
  }
885
894
  function findMacroArtifactModule(state, realPath, ssr, kind) {
886
895
  const cache = getEnvironmentCache(state, ssr);
896
+ const extractCss = shouldExtractCssForRequest(state, ssr);
887
897
  realPath = classifyVitePluginRequest(realPath).normalizedVuePath;
888
898
  let compiled = cache.get(realPath) ?? state.cache.get(realPath) ?? state.ssrCache.get(realPath);
889
899
  if (!compiled && fs.existsSync(realPath)) {
890
900
  const source = fs.readFileSync(realPath, "utf-8");
891
901
  compiled = compileFile(realPath, cache, getCompileOptionsForRequest(state, ssr), source);
892
- syncCollectedCssForFile(state, realPath, compiled);
893
902
  }
903
+ syncCollectedCssForFile({
904
+ ...state,
905
+ extractCss
906
+ }, realPath, compiled);
894
907
  return compiled?.macroArtifacts?.find((artifact) => artifact.kind === kind)?.moduleCode ?? null;
895
908
  }
896
909
  function hasNuxtComponentQuery(request) {
@@ -907,12 +920,16 @@ function loadCompiledSfcModule(state, realPath, isSsr, currentBase, loadOptions)
907
920
  };
908
921
  }
909
922
  const cache = getEnvironmentCache(state, isSsr);
923
+ const extractCss = shouldExtractCssForRequest(state, isSsr);
910
924
  let compiled = cache.get(realPath);
911
925
  if (!compiled && fs.existsSync(realPath)) {
912
926
  state.logger.log(`load: on-demand compiling ${realPath}`);
913
927
  compiled = compileFile(realPath, cache, getCompileOptionsForRequest(state, isSsr));
914
- syncCollectedCssForFile(state, realPath, compiled);
915
928
  }
929
+ syncCollectedCssForFile({
930
+ ...state,
931
+ extractCss
932
+ }, realPath, compiled);
916
933
  if (!compiled) return null;
917
934
  const hasDelegated = hasDelegatedStyles(compiled);
918
935
  const pendingHmrUpdateType = loadOptions?.ssr ? void 0 : state.pendingHmrUpdateTypes.get(realPath);
@@ -925,7 +942,7 @@ function loadCompiledSfcModule(state, realPath, isSsr, currentBase, loadOptions)
925
942
  isDev: state.server !== null && !isSsr,
926
943
  ssr: isSsr,
927
944
  hmrUpdateType: pendingHmrUpdateType,
928
- extractCss: state.extractCss,
945
+ extractCss,
929
946
  filePath: realPath
930
947
  });
931
948
  const output = rewriteStaticAssetUrls(rewriteDynamicTemplateImports(isSsr ? normalizeVueServerRendererImport(generatedOutput) : generatedOutput, state.dynamicImportAliasRules), state.dynamicImportAliasRules);
@@ -963,7 +980,8 @@ function loadHook(state, id, loadOptions) {
963
980
  if (id.startsWith("\0") && id.includes("?vue")) styleId = id.slice(1).replace(/\.module\.\w+$/, "").replace(/\.\w+$/, "");
964
981
  const styleRequest = classifyVitePluginRequest(styleId);
965
982
  if (styleRequest.isVueStyleQuery) {
966
- const realPath = classifyVitePluginRequest(styleRequest.path).vizeVirtualPath ?? styleRequest.path;
983
+ const sourceRequest = classifyVitePluginRequest(styleRequest.path);
984
+ const realPath = sourceRequest.vizeVirtualPath ?? sourceRequest.normalizedFsId ?? sourceRequest.normalizedVuePath ?? styleRequest.path;
967
985
  const lang = styleRequest.styleLang ?? null;
968
986
  const scoped = styleRequest.styleScoped ?? null;
969
987
  const fallbackCompiled = state.cache.get(realPath) ?? state.ssrCache.get(realPath);
@@ -1061,7 +1079,8 @@ function formatUnknownError(error) {
1061
1079
  }
1062
1080
  //#endregion
1063
1081
  //#region src/plugin/hmr.ts
1064
- const VIZE_COMPONENTS_CSS_FILE = "assets/vize-components.css";
1082
+ const VIZE_COMPONENTS_CSS_BASENAME = "vize-components.css";
1083
+ const VIZE_COMPONENTS_CSS_FILE = `assets/${VIZE_COMPONENTS_CSS_BASENAME}`;
1065
1084
  async function handleHotUpdateHook(state, ctx) {
1066
1085
  const { file, server, read } = ctx;
1067
1086
  if (file.endsWith(".vue") && state.filter(file)) try {
@@ -1134,21 +1153,27 @@ function handleGenerateBundleHook(state, emitFile, bundle) {
1134
1153
  let allCss = "";
1135
1154
  for (const css of state.collectedCss.values()) allCss += allCss ? `\n\n${css}` : css;
1136
1155
  if (allCss.trim()) {
1156
+ const cssFileName = state.componentsCssFileName || VIZE_COMPONENTS_CSS_FILE;
1137
1157
  emitFile({
1138
1158
  type: "asset",
1139
- fileName: VIZE_COMPONENTS_CSS_FILE,
1159
+ fileName: cssFileName,
1140
1160
  source: allCss
1141
1161
  });
1142
- attachComponentsCssToEntryChunks(bundle);
1143
- state.logger.log(`Extracted CSS to ${VIZE_COMPONENTS_CSS_FILE} (${state.collectedCss.size} components)`);
1162
+ attachComponentsCssToEntryChunks(bundle, cssFileName);
1163
+ state.logger.log(`Extracted CSS to ${cssFileName} (${state.collectedCss.size} components)`);
1144
1164
  }
1145
1165
  }
1146
- function attachComponentsCssToEntryChunks(bundle) {
1166
+ function resolveComponentsCssFileName(assetsDir) {
1167
+ const normalizedAssetsDir = (assetsDir || "assets").replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
1168
+ if (!normalizedAssetsDir || normalizedAssetsDir === ".") return VIZE_COMPONENTS_CSS_BASENAME;
1169
+ return `${normalizedAssetsDir}/${VIZE_COMPONENTS_CSS_BASENAME}`;
1170
+ }
1171
+ function attachComponentsCssToEntryChunks(bundle, cssFileName) {
1147
1172
  for (const item of Object.values(bundle)) {
1148
1173
  if (item.type !== "chunk" || !item.isEntry && !item.isDynamicEntry) continue;
1149
1174
  item.viteMetadata ??= {};
1150
1175
  item.viteMetadata.importedCss ??= /* @__PURE__ */ new Set();
1151
- item.viteMetadata.importedCss.add(VIZE_COMPONENTS_CSS_FILE);
1176
+ item.viteMetadata.importedCss.add(cssFileName);
1152
1177
  }
1153
1178
  }
1154
1179
  //#endregion
@@ -1208,13 +1233,17 @@ function createPostTransformPlugin(state) {
1208
1233
  state.logger.log(`post-transform: compiling virtual SFC content from ${id}`);
1209
1234
  try {
1210
1235
  const isSsr = !!transformOptions?.ssr;
1236
+ const extractCss = shouldExtractCssForRequest(state, isSsr);
1211
1237
  const compiled = compileFile(id, getEnvironmentCache(state, isSsr), getCompileOptionsForRequest(state, isSsr), code);
1212
- syncCollectedCssForFile(state, id, compiled);
1238
+ syncCollectedCssForFile({
1239
+ ...state,
1240
+ extractCss
1241
+ }, id, compiled);
1213
1242
  const result = await transformWithOxc(generateOutput(compiled, {
1214
1243
  isProduction: state.isProduction,
1215
1244
  isDev: state.server !== null,
1216
1245
  ssr: isSsr,
1217
- extractCss: state.extractCss,
1246
+ extractCss,
1218
1247
  filePath: id
1219
1248
  }), id, {
1220
1249
  lang: "ts",
@@ -1288,9 +1317,14 @@ function patchCssModuleGenerateScopedName(userConfig) {
1288
1317
  if (!cssModules || typeof cssModules.generateScopedName !== "function") return;
1289
1318
  const origFn = cssModules.generateScopedName;
1290
1319
  cssModules.generateScopedName = function(name, filename, css) {
1291
- return origFn.call(this, name, normalizeViteCssModuleFilename(filename), css);
1320
+ return origFn.call(this, name, normalizeCssModuleFilename(filename), css);
1292
1321
  };
1293
1322
  }
1323
+ function normalizeCssModuleFilename(filename) {
1324
+ const normalized = normalizeViteCssModuleFilename(filename);
1325
+ if (normalized.startsWith("/@fs/")) return normalized.slice(4);
1326
+ return normalized;
1327
+ }
1294
1328
  //#endregion
1295
1329
  //#region src/plugin/dev-middleware.ts
1296
1330
  function installVirtualAssetMiddleware(devServer, state) {
@@ -1362,6 +1396,13 @@ function mergeSharedConfig(baseConfig, overrideConfig) {
1362
1396
  entries: [...baseConfig.entries, ...overrideConfig.entries]
1363
1397
  };
1364
1398
  }
1399
+ function shouldExtractCssForBuild(state, context) {
1400
+ if (!state.isProduction) return false;
1401
+ const environmentName = context.environment?.name;
1402
+ if (environmentName === "client" || environmentName === "browser") return true;
1403
+ if (environmentName === "ssr" || environmentName === "server") return false;
1404
+ return state.extractCss;
1405
+ }
1365
1406
  function vize(options = {}) {
1366
1407
  if (isLegacyVueCompatibilityMode(options)) return [createLegacyVueCompatibilityPlugin(options)];
1367
1408
  const state = {
@@ -1384,6 +1425,7 @@ function vize(options = {}) {
1384
1425
  dynamicImportAliasRules: [],
1385
1426
  cssAliasRules: [],
1386
1427
  extractCss: false,
1428
+ componentsCssFileName: "assets/vize-components.css",
1387
1429
  clientViteDefine: {},
1388
1430
  serverViteDefine: {},
1389
1431
  logger: createLogger(options.debug ?? false)
@@ -1412,7 +1454,8 @@ function vize(options = {}) {
1412
1454
  const currentBase = resolvedConfig.command === "serve" ? options.devUrlBase ?? resolvedConfig.base ?? "/" : resolvedConfig.base ?? "/";
1413
1455
  if (isSsrBuild) state.serverViteBase = currentBase;
1414
1456
  else state.clientViteBase = currentBase;
1415
- state.extractCss = state.isProduction;
1457
+ state.extractCss = state.isProduction && !isSsrBuild;
1458
+ state.componentsCssFileName = resolveComponentsCssFileName(resolvedConfig.build.assetsDir);
1416
1459
  const isSsr = !!resolvedConfig.build?.ssr;
1417
1460
  const envDefine = {};
1418
1461
  if (resolvedConfig.define) for (const [key, value] of Object.entries(resolvedConfig.define)) {
@@ -1496,7 +1539,10 @@ function vize(options = {}) {
1496
1539
  },
1497
1540
  async buildStart() {
1498
1541
  if (!state.scanPatterns || state.scanPatterns.length === 0) return;
1499
- await compileAll(state);
1542
+ await compileAll({
1543
+ ...state,
1544
+ extractCss: shouldExtractCssForBuild(state, this)
1545
+ });
1500
1546
  state.logger.log("Cache keys:", [...state.cache.keys()].slice(0, 3));
1501
1547
  },
1502
1548
  resolveId(id, importer, options) {
@@ -1512,7 +1558,10 @@ function vize(options = {}) {
1512
1558
  return handleHotUpdateHook(state, ctx);
1513
1559
  },
1514
1560
  generateBundle(_, bundle) {
1515
- handleGenerateBundleHook(state, this.emitFile.bind(this), bundle);
1561
+ handleGenerateBundleHook({
1562
+ ...state,
1563
+ extractCss: shouldExtractCssForBuild(state, this)
1564
+ }, this.emitFile.bind(this), bundle);
1516
1565
  },
1517
1566
  closeBundle() {
1518
1567
  if (state.server === null) clearBuildCaches(state);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vizejs/vite-plugin",
3
- "version": "0.153.0",
3
+ "version": "0.155.0",
4
4
  "description": "High-performance native Vite plugin for Vue SFC compilation powered by Vize",
5
5
  "keywords": [
6
6
  "compiler",
@@ -39,9 +39,9 @@
39
39
  "access": "public"
40
40
  },
41
41
  "dependencies": {
42
- "@vizejs/native": "0.153.0",
42
+ "@vizejs/native": "0.155.0",
43
43
  "tinyglobby": "0.2.16",
44
- "vize": "0.153.0"
44
+ "vize": "0.155.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "25.7.0",