i18n cache incorrectly cleared (HMR/SSR mix)
When an Astro component that uses `@nanostores/i18n` messages is imported inside an MDX file, translations are missing or broken:
```
.astro -> .mdx -> .astro (broken at this level)
```
`define()` is designed to be called once at module level, outside a component's render function. However, MDX introduces an additional rendering layer: when an Astro component is embedded in MDX, `define()` ends up being called on every render rather than once at module load time.
In `create-i18n/index.js`, when `define()` is called and a cached entry for that component already exists, the code checks for HMR to decide whether to clear the cache:
```js
let isHMR = import.meta && (import.meta.hot || import.meta.webpackHot)
if (isHMR) {
/* c8 ignore next 3 */
for (let i in define.cache) {
delete define.cache[i][componentName]
}
} else if (!opts.isSSR) {
console.warn(`I18n component ${componentName} was defined multiple times. ...`)
}
```
In a Vite environment, `import.meta.hot` is always truthy. So every time MDX triggers a re-render of the Astro component, `define()` is called again, `isHMR` is `true`, and the entire cache for that component is wiped. The component ends up in an isolated context with an empty cache, as if it was never initialized, causing translations to be lost or always the provided default messages.
**Expected**
The HMR cache-clearing logic should not run when rendering server-side. In SSR, `import.meta.hot` being truthy is a Vite implementation detail and does not indicate a genuine HMR reload.
**Suggestion**
Guard the HMR cache-clear block with `!opts.isSSR`:
```js
let isHMR = import.meta && (import.meta.hot || import.meta.webpackHot)
if (isHMR && !opts.isSSR) {
/* c8 ignore next 3 */
for (let i in define.cache) {
delete define.cache[i][componentName]
}
} else if (!opts.isSSR) {
console.warn(`I18n component ${componentName} was defined multiple times. ...`)
}
```
**Environment**
- `@nanostores/i18n`: 1.3.2
- Framework: Astro 6 (SSR / MDX / Vite dev server)
关闭于 2026-05-10 2 条评论