Fix KaTeX extension loading by moving imports to app startup

• Move mhchem/copy-tex to main.tsx
• Add katex to Vite dedupe config
• Remove dynamic extension loading
• Ensure extensions available globally
• Fix chemistry formula rendering
This commit is contained in:
yangdx
2025-12-01 12:44:04 +08:00
parent 112ed234c4
commit 3f6423df33
3 changed files with 9 additions and 9 deletions

View File

@@ -76,21 +76,15 @@ export const ChatMessage = ({
? message.content
: (displayContent !== undefined ? displayContent : (message.content || ''))
// Load KaTeX dynamically with extensions
// Load KaTeX rehype plugin dynamically
// Note: KaTeX extensions (mhchem, copy-tex) are imported statically in main.tsx
useEffect(() => {
const loadKaTeX = async () => {
try {
// Load KaTeX extensions (must be loaded before rehype-katex)
// 1. mhchem: enables \ce and \pu commands for chemistry formulas
await import('katex/contrib/mhchem');
// 2. copy-tex: allows users to copy rendered formulas as LaTeX source code
await import('katex/contrib/copy-tex');
// Then load rehype-katex
const { default: rehypeKatex } = await import('rehype-katex');
setKatexPlugin(() => rehypeKatex);
} catch (error) {
console.error('Failed to load KaTeX plugin:', error);
// Set to null to ensure we don't try to use a failed plugin
setKatexPlugin(null);
}
};

View File

@@ -4,6 +4,9 @@ import './index.css'
import AppRouter from './AppRouter'
import './i18n.ts';
import 'katex/dist/katex.min.css';
// Import KaTeX extensions at app startup to ensure they are registered before any rendering
import 'katex/contrib/mhchem'; // Chemistry formulas: \ce{} and \pu{}
import 'katex/contrib/copy-tex'; // Allow copying rendered formulas as LaTeX source

View File

@@ -10,7 +10,10 @@ export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
// Force all modules to use the same katex instance
// This ensures mhchem extension registered in main.tsx is available to rehype-katex
dedupe: ['katex']
},
// base: import.meta.env.VITE_BASE_URL || '/webui/',
base: webuiPrefix,