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)