Syntax error: import declarations may only appear at top level of a module
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.
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
i'm trying to import a function from 'test.js' in 'index.js'
test.js:
var testFunction = function test(){ alert("hello World") } export testFunction
in the very top of 'index.js' i tried the following statement:
import testFunction from './test.js'
now i've got the following error in my firefox console, when i'm running my index.html file in the browser:
SyntaxError: import declarations may only appear at top level of a module (in line 1)