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()
1
  • What environment are you even using (nodejs, browser, something else)? Please show us how you load/call the app.js module. Commented Nov 17, 2019 at 19:37

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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;

2 Comments

"So, im trying to import hello() from hello.js.. ". OP does not use .mjs file extensions. Your answer might not work.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.