DEV Community 👩‍💻👨‍💻

Koutaro Chikuba
Koutaro Chikuba

Posted on

Off thread markdown rendering with Comlink

demo https://markdown-buffer.netlify.com/

tl;dr

remark in web worker with comlink(https://github.com/GoogleChromeLabs/comlink)

yarn add remark remark-html comlinkjs

(I use parcel-bundler to build)

Worker Side

src/worker.js

import remark from "remark";
import html from "remark-html";
import * as Comlink from 'comlinkjs'

const processor = remark().use(html)

class MarkdownCompiler {
  compile(raw) {
    return processor.processSync(raw).toString();
  }
}

Comlink.expose(MarkdownCompiler, self);

Main Thread

src/index.js

import * as Comlink from 'comlinkjs'

const MarkdownCompiler = Comlink.proxy(new Worker("./worker.js"));

const main = async () => {
  const compiler = await new MarkdownCompiler();
  const result = await compiler.compile('**your markdown here**');
  console.log(result)
}
main();

Comlink hides postMessage to make worker easy

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!