wooorm / parse-entities

Parse HTML character references
MIT License
49 stars 12 forks source link

Use in a web worker #16

Closed dancerphil closed 5 years ago

dancerphil commented 5 years ago

I'm using web worker to highlight code, but in some case, refractor tried to use document and failed since we do not have document in web worker.

It is quite difficult to reproduce this bug because it only happens to a huge file and I don't know which line cause this problem.

I think the error may help:

in ReferenceError: document is not defined
    at decodeEntity (decode-entity.browser.js:15)
    // node_modules/parse-entities/decode-entity.browser.js

    at parse (index.js:251)
    // node_modules/parse-entities/index.js

    at parseEntities (index.js:110)
    // node_modules/parse-entities/index.js

    at attributes (core.js:214)
    // node_modules/refractor/core.js

    at Function.stringify (core.js:176)
    // node_modules/refractor/core.js

    at stringifyAll (core.js:200)
    // node_modules/refractor/core.js

    at Function.stringify (core.js:155)
    // node_modules/refractor/core.js

    at Refractor.highlight (prism-core.js:277)
    // node_modules/prismjs/components/prism-core.js

    at Refractor.highlight (core.js:119)
    // node_modules/refractor/core.js

    at highlightText (index.js:7)
    // my own code

It will be grateful if you know why and how to fix it.

If not, I could help find some reproduce.

wooorm commented 5 years ago

Hi there, welcome!

If you are in a web worker, you can’t use document, indeed. We support browsers and non-browsers. Your bundler (such as Webpack / Rollup / Browserify) picks up on this (by default it’ll pick the browser version). If you are planning to bundle something for a web worker, you should tell your bundler to not pickup the browser version. How to do that, depends on your bundler, for webpack, it’s described here I think.