0

I'm a self-study student and having "Cannot use import statement outside a module-javascript" error So, im trying to import hello() from hello.js..

///////////hello.js///////
export default function hello(){
    console.log("hello")
}

////////////app.js/////////
import hello from "./hello"
hello()
  • What environment are you even using (nodejs, browser, something else)? Please show us how you load/call the `app.js` module. – Bergi Nov 17 '19 at 19:37

2 Answers2

2

import and export require script type set as module to work, unless you transpile it. Try this :

<script type="module" src="app.js"></script> 

which is equivalent to:

<script type="module">
    import hello from "./hello"
    hello()
</script>
Easwar
  • 3,409
  • 1
  • 7
  • 20
1

I am assuming you are using modules or mjs files in a browser environment and for that you just need get the syntax right.

Say you have an x html page and you want to import a module there:

<script type="module">
    import { hello } from "/hello.mjs"
        hello();
</script>

And export the module you want to use in your x html page as such:

export const hello = hello;
rags2riches
  • 1,420
  • 1
  • 7
  • 17
  • *"So, im trying to import hello() from* **hello.js..** *"*. OP does not use `.mjs` file extensions. Your answer might not work. – Emiel Zuurbier Nov 17 '19 at 21:28
  • I have said, "I am assuming you are using modules mjs file extension in a browser environment" and if that is correct, my suggestion works. If you are saying otherwise, you need to provide more context to your question. – rags2riches Nov 17 '19 at 22:53