Home > Software engineering >  How to impoort js type code into another js
How to impoort js type code into another js

Time:06-17

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

I want to import 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

CodePudding user response:

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 :Documentation mdn about export

CodePudding user response:

Assuming index.js and Sprite.js is on the same root directory,

Lets say your file "Sprite.js" looks like the following,

const Sprite = () => {
  const someInformation = "Hello World";
  return someInformation;
}

const SpriteAnother = () => {
  const someInformationAgain = "Hi World"!;
  return someInformationAgain;
}

export default Sprite;
export {SpriteAnother};

In this case, if you are trying to import from "Sprite.js" to another file "index.js", the valid import statements will be the following, inside "index.js"

import {SpriteAnother} from "./Sprite"
import Sprite from "./Sprite"

// your rest of the code goes here

Let me if it worked or not.

CodePudding user response:

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!

  • Related