javascripttypescriptumd

import @material js library via CDN


I'm trying to import material design into my project using import maps.

But I have run into problems. I'm trying to import it via importmap, but since all material components are inside @material/[component] namespaces, but the CDN from Material design documenation proxyes to a module (UMD if i remember corectly) which is a single file which contains all those namespaces as exports.

For example:

import { MDCList } from '@material/list';
const l = new MDCList(...);

Is Equivalent to:

import { list } from 'material-design-web';
const l = new list.MDCList(...);

But there is no CDN for @material as far as I know, so is there is a way, to tell it to treat the content after the slash like a namespace inside the module?

somethink like this:

<script type="importmap">
{
   "imports": {
       "@@material/": "https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"
    }
}
</script>

but this throws an error: Uncaught TypeError: Failed to resolve module specifier "@material/list". Import Map: "@material/list" matches with "@material/" but is blocked by a null value

is there a way around this? Or do I have to just forget about using CDN? (Whitout changing the inputs)


Solution

  • So for the CDN version, it looks like there are no paths for it follow.

    Instead all of the modules underneath paths have been web-packed into the root module, so for your particular module import you'd do this:

    Import map

    <script type="importmap">
    {
       "imports": {
           "@material/": "https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"
        }
    }
    </script>
    
    

    Then later

    import { list as MDCList } from "@material"
    

    As an aside, I ran into the same error Failed to resolve module specifier ... but is blocked by a null value with a slightly different circumstance. In my case it was that I didn't add a trailing slash to the right hand side of my import map entry.

    EX: had this: "tools/" : "./tools" But instead needed this : "tools/" : "./tools/" note the additional slash.


    For your case in particular you'd need either a local path or remote CDN that served the non-webpacked module file tree. Then you'd be able to do something like:

    "imports": {
           "@material/": "https://fake-magic-cdn.com/material-components/"
        }
    

    ...

    import { MDCList } from '@material/list';
    
    

    However, since your CDN serves a web-packed version, instead use the setup provided in first part of answer.