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.
-
How do you load b.js ? Is it from a web page in a browser? Is it running server-side in node.js?floverdevel– floverdevel2020年02月11日 03:29:43 +00:00Commented Feb 11, 2020 at 3:29
-
run in vscode node.jsTTT– TTT2020年02月11日 03:32:10 +00:00Commented Feb 11, 2020 at 3:32
2 Answers 2
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
Comments
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"
3 Comments
node index.js or whatever your filename is