Loading syntax highlighting on demand?

Hiya! I’ve noticed that when loading CM, a bevy of language parsers, from @lezer to @codemirror/legacy-modes.

I can use something like Vite to chunk the languages and load them separately. But what I can’t figure out is how to load the parser on demand. For example, if I allow a user to write markdown, and the write

backtick-backtick-backtick javascript

Is there an efficient (and, hopefully, prebuilt) way to load the JS highlighting once there’s a keyup on that final t?

Many thanks for any help.

All the language descriptions in @codemirror/language-data use dynamic imports. So if your bundler supports code splitting, they should just magically get loaded on demand.

Hm, I must be doing something wrong then. Is CodeMirror Bundling Example still the best documentation for learning more about this?

To expand on the original question: we’re doing this within a Markdown context. We import { languages } from "@codemirror/language-data"; and pass that into codeLanguages. But we don’t necessarily know which of those imported languages ought to be loaded, until a user begins writing a pre block with syntax highlighting.

Yes, that’s the idea. Each of these holds a function that, when called, runs an import(...) expression that fetches the actual language mode. If you set up Rollup or whatever you’re using to split your bundle on dynamic imports, they shouldn’t be part of the ‘main’ bundle.