HomeAbout MeContact

Loading CSS inside ES Modules

By Aditya Subramanyam
Published in Javascript
June 19, 2023
1 min read
Loading CSS inside ES Modules

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();

Tags

javascriptcssimport-map
Previous Article
How to fix "ReferenceError: __dirname/__filename/require is not defined in ES module scope"
Aditya Subramanyam

Aditya Subramanyam

Architect

Topics

Javascript

Related Posts

How to fix "ReferenceError: __dirname/__filename/require is not defined in ES module scope"
February 22, 2023
1 min

Quick Links

Advertise with usAbout UsContact Us

Social Media