1

I searched whole stackoverflow to fix it, but cant. So... I need to use NPM module in browser (index.html).

Getting error "require is not defined" if using

<script src="./script.js"></script>

in html file, and using const { WebcastPushConnection } = require('tiktok-livestream-chat-connector'); in script.js.

Tried to use browserify, and when i use outputed js script getting error "require.resolve is not a function"

Can anyone help?

lep1k
  • 11
  • 5
  • You can try something like Svelte to achieve what you want. You can also try including a CDN for the NPM package to use. – kerolloz Mar 01 '22 at 11:56
  • Is it even supposed to run in a browser? – Bravo Mar 01 '22 at 11:57
  • See [here](https://stackoverflow.com/questions/6971583/node-style-require-for-in-browser-javascript) for a similar question. Long story short; require won't directly work in the browser, you need to use something like webpack to bundle your JS for the browser if you want to use require. – HumanTarget Mar 01 '22 at 12:04
  • 1
    @HumanTarget — They're already using Browserify (which is something like webpack) – Quentin Mar 01 '22 at 12:07
  • @Quentin right you are, my mistake – HumanTarget Mar 01 '22 at 13:40

1 Answers1

0

tiktok-livestream-chat-connector is described, by its website, as:

A Node.js module to receive and decode livestream events like comments and gifts in realtime from TikTok LIVE by connecting to TikTok's internal WebCast push service.

At no point in its documentation does it mention compatibility with web browsers.

Browserify (and similar tools) can bundle up CommonJS modules into a single file so that they can run in environments which don't support CommonJS modules (e.g. browsers). They can't polyfill all the Node.js features that browsers don't support (like the ability to make raw socket network connections).

If a module needs to run on Node.js then you can't just move it to the browser.

You could write a program for Node.js that runs as a web service and operates as a bridge to whatever the module does. The the browser could connect to your web service with WebSockets or Ajax requests. The project links to an example of one.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335