TTT
TTT

Reputation: 53

Javascript Module error SyntaxError: Cannot use import statement outside a module

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.

Upvotes: 2

Views: 1806

Answers (2)

Alvin Zachariah
Alvin Zachariah

Reputation: 540

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

Upvotes: 3

Karma Blackshaw
Karma Blackshaw

Reputation: 942

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"

Upvotes: 0

Related Questions