When working with ES Modules and Import maps on the frontend, you will need to add CSS manually using `link` tags. This defeats the purpose of import-maps if we have add the css required by individually inside the HTML.
However, there is a better way to handle this. You can use @subbu963/import-map-utils
to auto load css files from inside modules itself.
This is how you can do it:
In your html file add the following script(where assetsRoot
is the path from which you css is served from) and import map:
<html> <head> ... <script> window.__importMapUtils = { css: { assetsRoot: '/assets/' } }; </script> <script type="importmap"> { "imports": { "import-map-utils/": "https://cdn.jsdelivr.net/npm/@subbu963/import-map-utils@0.1.4/lib/" } } </script> ... </head> ... </html>
Then in your ES Module import your css files like this:
import styles from 'import-map-utils/css/loader.js?src=./main.css'; // Now styles are auto injected into the DOM // Some code // You can also unmount your styles if you want to do a cleanup like this styles.unmount(); // You can remount it using styles.mount();
Quick Links
Legal Stuff