2

I am trying to test simple export and importsample.

//file   a.js

export const a = 2

//file   b.js

import {a} from './a.js'


console.log(a);

But it show error

import {a} from './a.js'

^^^^^^

SyntaxError: Cannot use import statement outside a module

I use vscode to test this.

a.js and b.js is in the same folder.

I have no idea to this.

Community
  • 1
  • 1
TTT
  • 53
  • 7

2 Answers2

3

If you are on browser try @karma Blackshaw 's answer . If your are using node add "type": "module" to your package.json . Or you can change extension of your .js files to .mjs and run with --experimental modules flag

a.mjs

//file   a.mjs

export const a = 2

b.mjs:

import {a} from './a.mjs'


console.log(a);

and run using :

node --experimental-modules b.mjs

Read docs

Alvin Zachariah
  • 540
  • 3
  • 12
0

I solved this issue by doing the following:

When using ES6 modules from browser use .js extension in your files and in script tag add type = "module"

Karma Blackshaw
  • 880
  • 8
  • 20
  • Is it possible to run javascript node.js in vscode? It still show same error. I try your way in Chrome, it's work! – TTT Feb 11 '20 at 03:24
  • yes. You can open the command line in your current directory and type `node index.js` or whatever your filename is – Karma Blackshaw Feb 11 '20 at 03:27
  • [This](https://stackoverflow.com/questions/6737824/how-to-run-a-hello-js-file-in-node-js-on-windows) will give you a head start – Karma Blackshaw Feb 11 '20 at 03:28