简体   繁体   中英

MathJax with WebPack ReferenceError: require is not defined

I would like to put formulas in my webpage, which uses (dotnet Kestrel). I do not want to load javascript libraries from the net, so I am using webpack and npm for my packages. My problem is, that I find it impossible to load MathJax. I have tried the following:

import 'mathjax-full';
require('mathjax-full'); // << not the error itself
import MathJax from 'mathjax-full';

The most annoying error that I get is this:

ReferenceError: require is not defined

I must do something obviously wrong. The error message comes from the MathJax internals. I have also tried to import requirejs , as some forums mentioned that as some kind of "workaround". The error I get with it is when I run WebPack:

ERROR in ./node_modules/requirejs/bin/r.js 1:0
Module parse failed: Unexpected character '#' (1:0) 

Has anybody succeeded with MathJax on WebPack?

I've encountered the same problems as you plus a million more. MathJax is really not WebPack-friendly.

My solution for Angular:

npm install --save mathjax

Extend the "scripts" array of angular.json with:

"node_modules/mathjax/es5/tex-mml-chtml.js"

And now to call MathJax APIs, DO NOT use import of any kind. The mathjax module sets its main to es5/node-main.js , which uses an ugly hack to call require() at runtime, which is the ultimate source of trouble you saw.

Instead, do this:

declare var MathJax;

Now you may complain that this way you have no type information. Well, the fact is that not even mathjax-full has good type information for methods inside this global object: they inject the methods (such as MathJax.typeset() ) at runtime and their types are declared using [name: string]: any; .

If your really want type information, you're probably better off declaring it yourself, eg:

declare interface MathJaxGlobal {
  typeset(elems: HTMLElement[]);
}
declare var MathJax: MathJaxGlobal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM