5

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)

Davis D. Sky
  • 61
  • 1
  • 1
  • 4
  • 1
    What's the context? A browser? How exactly are the scripts being referenced? – Pointy Jan 17 '20 at 14:46
  • 2
    Do you have `type="module"` set for the script element containing the import statement? Also, the import is importing a default export, but that can't be seen in the test.js file. – Teemu Jan 17 '20 at 14:47
  • Yeah, i've got this error in my firefox browser console. I have an index.html file: ``` – Davis D. Sky Jan 18 '20 at 12:29

2 Answers2

9

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.

K_Wainaina
  • 219
  • 3
  • 7
1

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">

Community
  • 1
  • 1
Davis D. Sky
  • 61
  • 1
  • 1
  • 4
  • I tried this, but the moment I add type="module" inside – Mazhar MIK Apr 25 '20 at 12:15
  • that's another topic, your request is send from an adress which isn't the same adress where your server is running on... try to set request/response header: Access-Control-Allow-Origin : * – Davis D. Sky Oct 14 '20 at 14:37