Import source.js file (previous AllPackages) with bundler
In MathJax v4.0.0-beta.7 AllPackages.ts file was removed, and the document provide two ways to construt it manually
for the browser
<script type="importmap">
{
"imports": {
"#source/source.cjs": "https://cdn.jsdelivr.net/npm/[email protected]/components/mjs/source-lab.js"
}
}
</script>
<script type="module">
import {source} from 'https://cdn.jsdelivr.net/npm/[email protected]/components/mjs/source.js';
const load = Object.keys(source).filter((name) => name.substring(0,6) === '[tex]/').sort();
const packages = ['base'].concat(load.map((name) => name.substring(6)));
window.MathJax = {
loader: {load},
tex: {packages}
};
</script>
the document import the source.js file from CDN
But I use the mathjax-full package in my frontend project, and use Vite as the bundler, and want to import the source.js from the local package
and refer to the document for node app, use the following code to import source.js
import {source} from 'mathjax-full/components/src/source.js';
const AllPackages = Object.keys(source).filter((name) => name.substring(0,6) === '[tex]/').sort();
but the console throw the error like this
[!CAUTION] Uncaught ReferenceError: __dirname is not defined
I check out the /components/mjs/source.js file, and find that it import the src from the source.cjs, which use the __dirname and only available at node environment
if any other way to import the source.js file for frontend project without using the CDN
Note that the code you quote from the beta.7 release notes includes an import map that redirects source.cjs to source-lab.js, so one possibility would be to use that file to set the value of __dirname that source.cjs needs. For example:
global.__dirname = (await import('@mathjax/src/components/mjs/source-lab.js')).src;
const {source} = await import('@mathjax/src/components/mjs/source.js');
delete global.__dirname;
const load = Object.keys(source).filter((name) => name.substring(0,6) === '[tex]/').sort();
const packages = ['base'].concat(load.map((name) => name.substring(6)));
console.log(packages);
Here I've just printed the package list, but you can use it in your configuration as in the code you cite.
Alternatively, you can in-line the code from source-lab.js, since it is only one line:
global.__dirname = String(new URL('.', import.meta.url)).replace(/\/$/, '');
const {source} = await import('@mathjax/src/components/mjs/source.js');
delete global.__dirname;
const load = Object.keys(source).filter((name) => name.substring(0,6) === '[tex]/').sort();
const packages = ['base'].concat(load.map((name) => name.substring(6)));
console.log(packages);
If you don't want to use await, you will need to put the first line (of either example) into a separate file and import that.