Search code examples
es6-modulesvee-validate

How to use ES6 import (client-side JS)


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?


Solution

  • 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: