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.

2
  • How do you load b.js ? Is it from a web page in a browser? Is it running server-side in node.js? Commented Feb 11, 2020 at 3:29
  • run in vscode node.js Commented Feb 11, 2020 at 3:32

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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"

3 Comments

Is it possible to run javascript node.js in vscode? It still show same error. I try your way in Chrome, it's work!
yes. You can open the command line in your current directory and type node index.js or whatever your filename is
This will give you a head start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.