Davis D. Sky
Davis D. Sky

Reputation: 141

Syntax error: import declarations may only appear at top level of a module

I'm trying to import a function from test.js in index.js, which then is imported by index.html.

test.js

var testFunction = function test() {
    alert("hello World")
}

export testFunction

index.js

import testFunction from './test.js'
...

index.html

...
<script src="./index.js"></script>
...

When opening index.html the following error is thrown:

SyntaxError: import declarations may only appear at top level of a module

Upvotes: 10

Views: 40617

Answers (2)

K_Wainaina
K_Wainaina

Reputation: 309

There's two ways: Solution 1(Default export):

test.js

var testFunction = function test() {alert('hello world')}

export default testFunction;

You can also do export default function() {alert('hello world')};

index.js

import testFunction from './test.js'

Solution 2(Named export):

test.js

var testFunction = function test() {alert('hello world')};

export { testFunction };

index.js

import { testFunction } from './test.js'

In both situations your html file has <script type="module" src="./index.js"></script>

The above line rectifies the syntaxError: Import declarations may only appear at top level of module. It's because when you import, the file now becomes a module. Your index.js file is now the top-level module.

If you do this and get the Cross-Origin Request Block error. You should do your work through a server.

Further reading on modules.

Upvotes: 12

Davis D. Sky
Davis D. Sky

Reputation: 141

Solution:

test.js

var testFunction = function test(){ alert("hello World") }

export {testFunction}


index.js:
import testFunction from './test.js'

//...

html:
<script type="module" src="./index.js">

Upvotes: 4

Related Questions