15

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?

rrebase
  • 3,349
  • 2
  • 16
  • 27

4 Answers4

13

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 96% of all users browser (caniuse.com).

Documentation:

TOPKAT
  • 6,667
  • 2
  • 44
  • 72
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

Chris - Jr
  • 398
  • 4
  • 11
0

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

Gene Yuss
  • 33
  • 5
-1

Try this :

const url = './demo.js';
try { import(url).loadPageInto(main);} 
catch (error) { main.textContent = error.message; }