Import css with css module scripts in esm
Traditionally there are a few ways to statically add css to a page, and via JavaScript it can also be dynamically added by either creating a link
element with rel="stylesheet"
and href
set to a css file location, or creating a style
element with css definitions as its content. Now there is a 3rd way: importing css directly from within an ESM script tag, similarly to the way of importing JavaScript resources, via a feature called CSS Module scripts
.
Example
<div id="app" class="has-text-success">{{ message }}</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
import bulma from 'https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css' assert { type: 'css' };
document.adoptedStyleSheets.push(bulma);
createApp({
data() {
return {
message: 'Hello World!'
}
}
}).mount('#app');
</script>
References