How to use ES6 import (client-side JS)
Asked Answered
B

4

16

I am trying to use VeeValidate and the examples show the usage of ES6 import like this:

import { Validator } from 'vee-validate';

My understanding is that this works only with npm and not with CDN. I want to just write client-side js and not use node js. Do I have to look into something like browserify or webpack?

I tried to copy the javascript from the CDN link and just make it a local js file for importing, but could not get it working. Did it not work because I did not have export statements?

Borborygmus answered 2/3, 2018 at 21:19 Comment(1)
If you copy in your local you need to specify path also by default it looks inside node_modules.Coe
P
14

The first thing to do is to put type="module" as an attribute of your <script> tag

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.

Currently import / export syntax is supported by 97+% of all users browser (caniuse.com).

Documentation:

Postage answered 7/7, 2018 at 18:52 Comment(1)
Is it necessary to import 'module-a.mjs' first in order to use it in the module 'module-b.mjs'?Durant
H
1

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

Hernardo answered 5/3, 2018 at 13:22 Comment(0)
M
0

This method for loading modules locally (i.e. client-side) unfortunately gets blocked by CORS in Chrome and Chromium based browsers.

Maddocks answered 5/3, 2023 at 18:41 Comment(0)
S
-1

Try this :

const url = './demo.js';
try { import(url).loadPageInto(main);} 
catch (error) { main.textContent = error.message; }
Swale answered 14/3, 2019 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.