"Failed to resolve module specifier "openai". when using VS code live server?

Hello everyone, I know I’m doing something painfully obvious wrong but I’ve scoured the net for two days and can’t find a solution. From what I can understand it’s a path issue but I still don’t know how to resolve it.

Here is my JS:

import OpenAI from 'openai'

const openai = new OpenAI({
    apiKey: '123456'
})

console.log(openai.apiKey)

Here is my HTML

<!DOCTYPE html>

<html lang="en">
  <head>
    <script src="index.js" type="module"></script>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
</html>

And here is a screen shot of what I put in the terminal

Thanks in advance for any help you can provide!

Hi!

Typically when you install a package with npm you should have a node_modules folder and a package.json file, I don’t see either in your project.

I don’t know if the library actually works in the front end - in either case, it’s not a good idea to use it as such. You’ll probably want a node server.

Have you considered asking GPT how to set up a minimal javascript project?

3 Likes

Thanks for that! I’ve asked GPT how to set up a minimal javascript project and followed all the steps. It’s working and I can see “hello” logged in the console when I open my index.html file in the browser. However, I’m still getting the same error when I change the code in app.bundle.js to try and import OpenAI for ‘openai’

What is intresting is that i’m getting two different errors, one when i open it with live server " “Failed to resolve module specifier “openai”
Another when I just open the index.html in chrome. “Access to script at ‘file:///Users/admin/my-js-project/app.js’ from origin ‘null’ has been blocked by CORS policy”

Here is a screenshot where you can see both errors. Any ideas? :thinking:

yeah the easiest option is probably to launch your html from live preview (it’s an extension by msft)

but maybe try to get your node server to spit a hello world into your terminal, then print your openai result into your console, and then you can start looking into connecting stuff to your front end

If you’re completely new to this it’s not gonna be easy, but with enough tenacity i’m sure you can get there :slight_smile:

1 Like

I’m very green, but have a large amount of tenacity!

I have no problem getting it to log Hello World. The problem arises when I try to import OpenAI from ‘openai’. Here is a screenshot of printing Hello World

try to get a hello world into the terminal on the right :slight_smile:

Spoiler

package.json → scripts → “run”: “node your_file.js”

openai needs to live on your server, not in your browser

1 Like

OMG I did it! Thanks for holding my hand through that! Hopefully this thread helps some other greenies get going :sweat_smile:

2 Likes