How to use ES6 import (client-side JS)

rrebase picture rrebase · Mar 2, 2018 · Viewed 11.6k times · Source

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?

Answer

GLAND_PROPRE picture GLAND_PROPRE · Jul 7, 2018

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

You can use it to "include" your script. The first thing to do is to put type="module" as an attribute of a <script tag> (Eg. <script type="module">)

Then you can import/export in your js scripts. And YES modules need to export a value (variable, function...) to be able to use it in another script, but this is optionnal since you can just execute script without the need to export something.

Documentation:

Keep in mind that is not yet a fully supported feature and you will need a polyfill if you mind about browser compatibility