MathJax配置

这个真的难绷,官方文档看不懂,网上找的例子看似能行但实机起来各种奇怪的错误。目前mathjax是3x,但我尝试下来是行不通的。到现在,我有一个成功的案例,是mathjax@2的。分享如下:

index.html

<body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
    <!-- 识别单行,行内,\( \)样式的公式 -->
    <script>
        MathJax = {
            tex: {
                inlineMath: [
                    ['$', '$'],
                    ['$$', '$$'],
                    ['\\(', '\\)']
                ]
            }
        }
    </script>
    <script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</body>

utils

新建一个mathjax.ts

interface MathJaxConfigOptions {
    showProcessingMessages?: boolean
    messageStyle?: string
    jax?: string[]
    tex2jax?: {
        inlineMath: [string[], string[]]
        displayMath: [string[], string[]]
        skipTags: string[]
    }
    'HTML-CSS'?: {
        availableFonts?: string[]
        showMathMenu?: boolean
    }
}

let isMathjaxConfig: boolean = false

export const initMathjaxConfig = (): void => {
    if (!window.MathJax) {
        return
    }
    window.MathJax.Hub.Config({
        showProcessingMessages: false,
        messageStyle: 'none',
        jax: ['input/TeX', 'output/HTML-CSS'],
        tex2jax: {
            inlineMath: [
                ['$', '$'],
                ['\\(', '\\)']
            ],
            displayMath: [
                ['$$', '$$'],
                ['\\[', '\\]']
            ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
        },
        'HTML-CSS': {
            availableFonts: ['STIX', 'TeX'],
            showMathMenu: false
        }
    } as MathJaxConfigOptions)
    isMathjaxConfig = true
}

export const MathQueue = (elementId: string): void => {
    if (!window.MathJax) {
        return
    }
    window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, document.getElementById(elementId)])
}

export default {
    isMathjaxConfig,
    initMathjaxConfig,
    MathQueue
}

因为是ts,可能会有未知的报错,比方我之前一次实验的时候,便报错Window下没有MathJax这个type,我是在types下新建了一个global.d.ts

interface Window {
    MathJax?: any;
}

记得把global.d.ts在main.ts中挂载。

mathjax.vue

如果上述都ok的话,这步copy后再run起来,浏览器应该是直接就把公式渲染好了。

<script setup lang="ts">
import Mathjax from "@/utils/mathjax.ts";
import {ref, onMounted, nextTick} from "vue";

const mathjax = ref<string>('If $$ f(x) = f(a) + f\'(a)(x - a) + \\frac{f\'\'(a)}{2!}(x - a)^2 + \\frac{f^{(3)}(a)}{3!}(x - a)^3 + \\dots + \\frac{f^{(n)}(a)}{n!}(x - a)^n + R_n(x), $$ then this is the Taylor series expansion of \\( f(x) \\) around \\( a \\).\n');
onMounted(async () => {
  await nextTick(() => {
    if (Mathjax.isMathjaxConfig) {
      Mathjax.initMathjaxConfig()
    }
    Mathjax.MathQueue('mathjaxTest')
  })
})


</script>
<template>
  <el-row>
    <div class="mathjaxTest" v-html="mathjax"></div>
  </el-row>
</template>


<style scoped></style>
posted @ 2024-12-24 09:43  yapi_wwj  阅读(293)  评论(0)    收藏  举报