1

I'm trying to make an AI text generator (using an API) and it says "ReferenceError: require is not defined", and I don't have a package JSON or HTML outside of it because I'm running it from a Snap! JavaScript function reporter. Any ideas? I've thought of putting a function in the variable box, but I don't know what goes in there. Code:

const deepai = require('deepai'); // OR include deepai.min.js as a script tag in your HTML

deepai.setApiKey('quickstart-QUdJIGlzIGNvbWluZy4uLi4K');

(async function() {
    var resp = await deepai.callStandardApi("text-generator", {
            text: "YOUR_TEXT_HERE",
    });
    console.log(resp);
})()
Random Davis
  • 6,662
  • 4
  • 14
  • 24
OrrinPants
  • 69
  • 1
  • 7
  • `require()` is a function from `node.js`. If you aren't running this in node, then you need to do what the comment is telling you to ("include deepai.min.js as a script tag in your HTML") – ryan Oct 13 '22 at 15:47
  • @ryan — What HTML? The question says "I don't have a package JSON or HTML outside of it because I'm running it from a Snap! " – Quentin Oct 13 '22 at 15:52
  • I forgot about how I tried to do it this way. I achieved it with a Snap! server but it ran out of free credits. Yeah. A SCRIPT ran out of free credits. But it probably would've done that this way (question snippet) too. Thinking of making it fallback to another API if it runs out of credits. The snap block just detects if it says... oh wait it got its free credits back (moved from answer) – OrrinPants Oct 25 '22 at 21:56

1 Answers1

1

require is not a part of the JavaScript language.

It is an API provided by host environments supporting CommonJS modules (Node.js is the most common example).

If your host environment doesn't support it (as appears to be the case here) then you can't use it and need to rewrite the code using features available in the host environment you are using.

Sometimes it is possible to do this in an automated way. For example, Webpack and other bundler tools can transform JavaScript written using Node.js modules (providing they don't depend on Node.js-specific APIs like the fs module for accessing files) into single JS files that can run in web browsers and other host environments.

I've not heard of Snap! before, but the manual I found here says:

Snap!runs in JavaScript in your browser

… so that might be a way forward. You could also look for another way to load an external script into that environment.

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