I have a question which might seem trivial or stupid to many, yet for me it is complex and I just can't get my head around it.
I have some frontend javascript code, which I Html.RequiresJ(...) and all works nicely.
Now I want to use a javascript library from my js, in this case "js-cookie". I do anyother Html.RequiresJ(...) and the library's js file is loaded no problem.
The question is: how do I use the library code, which is a javascript module? In my javascript file, I would normally do
import Cookies from '/path/to/js.cookie.js'
but of course this gives a browser error:
Uncaught SyntaxError: Cannot use import statement outside a module
When I request my javascript file with the "type=module" option set, the import is accepted, but now I get
Uncaught SyntaxError: The requested module '/node_modules/js-cookie/dist/js.cookie.min.js' does not provide an export named 'default'
Trying to import it like this
import { Cookies } from '/path/to/js.cookie.js'
Gives me this error:
Uncaught SyntaxError: The requested module '/node_modules/js-cookie/dist/js.cookie.min.js' does not provide an export named 'Cookies'
How can I reference this (or any other) js library in my javascript? I am missing some basic understanding here :-(
Using a js module on frontend
I have a question which might seem trivial or stupid to many, yet for me it is complex and I just can't get my head around it.
I have some frontend javascript code, which I
Html.RequiresJ(...)
and all works nicely.Now I want to use a javascript library from my js, in this case "js-cookie". I do anyother
Html.RequiresJ(...)
and the library's js file is loaded no problem.The question is: how do I use the library code, which is a javascript module? In my javascript file, I would normally do
but of course this gives a browser error:
When I request my javascript file with the "type=module" option set, the
import
is accepted, but now I getTrying to import it like this
Gives me this error:
How can I reference this (or any other) js library in my javascript? I am missing some basic understanding here :-(
Kind regards, Mikael
Try:
import * as cookieModule from "/path/to/js.cookie.js";
or justimport "/path/to/js.cookie.js"
See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
is working on a reply...