From 4ee596806c0726d967434dbf2b190005e3448439 Mon Sep 17 00:00:00 2001 From: Sergio Brighenti Date: Fri, 15 Dec 2023 01:15:46 +0100 Subject: [PATCH] Fix hotreloading --- package.json | 2 +- src/index.ts | 2 +- src/vite.ts | 22 ++++++++++++++-------- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 70e8bc1..bd12752 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "laravel-translator", "type": "module", - "version": "0.0.1", + "version": "0.0.2", "description": "Laravel localization bridge for your frontend.", "main": "dist/index.cjs", "module": "dist/index.js", diff --git a/src/index.ts b/src/index.ts index f80f8da..bb29503 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,7 @@ const isServer = typeof window === 'undefined' const defaultConfig: Config = { locale: !isServer && document.documentElement.lang ? document.documentElement.lang.replace('-', '_') : 'en', - fallbackLocale: !isServer && window ? window?.fallbackLocale.replace('-', '_') : null, + fallbackLocale: !isServer && window ? window?.fallbackLocale?.replace('-', '_') : null, translations: translations, } diff --git a/src/vite.ts b/src/vite.ts index ad3da68..6b0aeca 100644 --- a/src/vite.ts +++ b/src/vite.ts @@ -16,7 +16,7 @@ export default function laravelTranslator(options: string | VitePluginOptionsInt const virtualModuleId = 'virtual:laravel-translations' const resolvedVirtualModuleId = '\0' + virtualModuleId - let translations = null + const paths = [frameworkLangPath, langPath, ...additionalLangPaths] return { name: 'laravelTranslator', enforce: 'post', @@ -27,16 +27,22 @@ export default function laravelTranslator(options: string | VitePluginOptionsInt }, load(id) { if (id === resolvedVirtualModuleId) { - if (!translations) { - translations = exportTranslations(frameworkLangPath, langPath, ...additionalLangPaths) - } - - return `export default ${JSON.stringify(translations)}` + return `export default ${JSON.stringify(exportTranslations(...paths))}` } }, handleHotUpdate(ctx) { - if (ctx.file === resolvedVirtualModuleId) { - translations = exportTranslations(frameworkLangPath, langPath, ...additionalLangPaths) + for (const lp of paths) { + const relative = path.relative(lp, ctx.file); + const isSub = relative && !relative.startsWith('..') && !path.isAbsolute(relative); + if (isSub) { + const virtualModule = ctx.server.moduleGraph.getModuleById(resolvedVirtualModuleId)!; + ctx.server.moduleGraph.invalidateModule(virtualModule) + ctx.server.ws.send({ + type: 'full-reload', + path: '*' + }); + return + } } } }