These are my sample files:
<!DOCTYPE html> <html> <head> <title>Test</title> <script src="t1.js"></script> </head> <body></body> </html>
t1.js:
import Test from 't2.js';
t2.js:
export const Test = console.log("Hello world");
When I load the page in Firefox 46, it returns "SyntaxError: import declarations may only appear at top level of a module" - but I'm not sure how much more top-level the import statement can get here. Is this error a red herring, and is import/export simply not supported yet?
The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error. Do not worry about the error!
Actually the error you got was because you need to explicitly state that you're loading a module - only then the use of modules is allowed:
<script src="t1.js" type="module"></script>
I found it in this document about using ES6 import in browser. Recommended reading.
Fully supported in those browser versions (and later; full list on caniuse.com):
In older browsers you might need to enable some flags in browsers:
chrome:flags
.dom.moduleScripts.enabled
setting in about:config
.about:flags
.This is not accurate anymore. All current browsers now support ES6 modules
From import
on MDN:
This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.
Browsers do not support import
.
Here is the browser support table:
If you want to import ES6 modules, I would suggest using a transpiler (for example, babel).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With