How to use ES6 import (client-side JS)
The issue, as you said is that import is currently only being supported globally via Node. If you want to quickly import code on the client side, and jQuery is an option, then you can use:
$.getScript( "ajax/test.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
This will load and execute the JavaScript code from the server. The callback done
is called when the script has finished downloading, but not necessarily completed execution.
For more info, you can look at the official reference
Currently import / export syntax is supported by 90% of all users browser (caniuse.com).
The first thing to do is to put type="module"
as an attribute of your <script>
tags (Eg. <script type="module">
)
Full example:
<script type='module' src='module-a.mjs' />
<script type="module">
import * as moduleA from 'module-a.mjs'
</script>
You may want to add a .mjs
extension to explicitly tell that this file is a js module and avoid syntax errors in your IDE.
Documentation:
- import
- export
- Very good article on how to use module in browsers