Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Mikael Axel Kleinwort 142 posts 487 karma points c-trib
    Nov 29, 2021 @ 08:12
    Mikael Axel Kleinwort
    0

    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

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

    Kind regards, Mikael

  • louisjrdev 11 posts 84 karma points
    Nov 29, 2021 @ 13:36
    louisjrdev
    0

    Try: import * as cookieModule from "/path/to/js.cookie.js"; or just import "/path/to/js.cookie.js"

    See MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Please Sign in or register to post replies

Write your reply to:

Draft