-1

I have 3 files: index.html, index.js, Sprite.js

I want to import Sprite class from Sprite.js into index.js

I've tryed this:

    import Sprite from "Sprite.js"

And also this:

    import Sprite from Sprite

When i open the html with Google Chrome it gives me this error:

Uncaugth SyntaxError: Cannot use import statement outside a module
  • Use `export` or `export default` in `Sprite.js` to export function, e.g. `export function test() {}`, then in `index.js` write `import { test } from './Sprite.js'` – rastiq Jun 17 '22 at 13:27
  • 3
    Don't post images, put the text into your question. And both of your screenshots are the same image. And you did not tell us what error you get. – takendarkk Jun 17 '22 at 13:27
  • Hi, welcome to Stack Overflow. We're glad you're here, but your post gives us a hard time understanding it in a way we can offer you help. Your question has to be reproducible or at least self-contained. Meaning all the information needs to be within this question itself. What is the server environment? What instance runs these scripts? Browser/website or Node,js? How would these files be accessible? Please read the ["How do I ask?" Guide](https://stackoverflow.com/help/how-to-ask) and add more information about the problem. – Niklas E. Jun 17 '22 at 13:34
  • @NiklasE. Thank you for your comments. This is my first post, so it probably has a lot of mistakes. I will try to make the correct changes to get better at posting questions, – Juan Pablo Arano Jun 17 '22 at 13:46
  • @JuanPabloArano Hey juan, I posted some answers, let me if those are working or not! Thanks – DanteDX Jun 17 '22 at 13:48

3 Answers3

1

@ Juan Pablo Arano There might be a problem when you want to use javascript modules out of modules context. The is almost no chance to achieve that without Webpack or npm. If you want to use a module out of a modules context, you need to use above compilators before you run the code.

The following can be useful:

How do I include a JavaScript file in another JavaScript file?

LucianDex
  • 469
  • 2
  • 12
0

You have to initially export your function to be able to import it in another file. It'll be very useful for every project, try to learn about it:
MDN export documentation

Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
Thomas ODE
  • 11
  • 1
0

After seeing your updated question with the error "Uncaugth SyntaxError: Cannot use import statement outside a module", you can use module.exports always for example, Sprite.js file will look like the following,

const Sprite = () => {
  console.log("Sprite function")
}

module.exports = Sprite;

Inside index.js file, you can just do,

const Sprite = require("./Sprite")

// your code goes here!
DanteDX
  • 1,059
  • 7
  • 12