From 2a58e9edcfcc158e6b1b557763148d53e1f7a636 Mon Sep 17 00:00:00 2001
From: mog422 <admin@mog422.net>
Date: Fri, 19 Jul 2024 16:29:46 +0900
Subject: [PATCH] fix: missing register component in ssr (#1887)

---
 package.json |  2 ++
 src/index.ts | 15 +++++++++++++++
 2 files changed, 17 insertions(+)

diff --git a/package.json b/package.json
index b36e30b00..69285a0c0 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,7 @@
   "packageManager": "pnpm@8.12.0",
   "dependencies": {
     "chalk": "^4.1.0",
+    "hash-sum": "^2.0.0",
     "watchpack": "^2.4.0"
   },
   "peerDependencies": {
@@ -57,6 +58,7 @@
     "@intlify/vue-i18n-loader": "^3.0.0",
     "@types/cssesc": "^3.0.2",
     "@types/estree": "^0.0.45",
+    "@types/hash-sum": "^1.0.2",
     "@types/jest": "^26.0.13",
     "@types/jsdom": "^16.2.13",
     "@types/mini-css-extract-plugin": "^0.9.1",
diff --git a/src/index.ts b/src/index.ts
index 890dc1cb3..44df75cf2 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -11,6 +11,9 @@ import type {
   SFCTemplateCompileOptions,
   SFCScriptCompileOptions,
 } from 'vue/compiler-sfc'
+
+import hashSum from 'hash-sum'
+
 import { selectBlock } from './select'
 import { genHotReloadCode } from './hotReload'
 import { genCSSModulesCode } from './cssModules'
@@ -363,6 +366,18 @@ export default function loader(
         .join(`\n`) + `\n`
   }
 
+  if (isServer) {
+    code += `\nimport { useSSRContext } from 'vue'\n`
+    code += `const _setup = script.setup\n`
+    ;(code += `script.setup = (props, ctx) => {`),
+      (code += `  const ssrContext = useSSRContext()`),
+      (code += `  ;(ssrContext._registeredComponents || (ssrContext._registeredComponents = new Set())).add(${JSON.stringify(
+        hashSum(loaderContext.request)
+      )});`)
+    code += `  return _setup ? _setup(props, ctx) : undefined`
+    code += `}\n`
+  }
+
   // finalize
   if (!propsToAttach.length) {
     code += `\n\nconst __exports__ = script;`