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?
Importing can be done in various ways: Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
Introduction to the JavaScript import() The import() allows you to dynamically import a module when needed. Here is how the import() works: The import() accepts a module specifier ( moduleSpecifier ) that has the same format as the module specifier used for the import statement.
With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.
ES6 module loaders will be asynchronous while node.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With