How to make Vite include CSS import statements in the built JavaScript file for a library

1 week ago 16
ARTICLE AD BOX

I'm building a TypeScript library with Vite that uses SCSS modules. I want the final built .js file to contain actual import "./style.css" statements at the top, so that when users import my library, the CSS is automatically loaded.

I made a minimal repo for testing: https://github.com/Ruminat/library-build-test

Here are the source files:

src/index.ts:

import styles from "./style.module.scss"; const element = document.createElement("div"); element.className = styles.myClass; element.textContent = "Hello from TypeScript + SCSS!"; document.body.appendChild(element);

src/style.module.scss:

.myClass { color: blue; padding: 20px; font-size: 18px; }

Currently, the build looks almost like I want it to. With only one problem: it doesn't include the final .css file import (the library end user has to import it himself).

My library has many entry points, and I don't want users to manually import CSS files for each entry point. I need the JavaScript files to automatically load their corresponding CSS.

How can I configure Vite (or other bundler) to produce JavaScript files that contain import "./style.css" statements at the top?

I want the final build to look like this:

dist/my-library.mjs:

import "./my-library.css"; const myClass = "style-module__myClass___el7An"; const styles = { myClass }; const element = document.createElement("div"); element.className = styles.myClass; element.textContent = "Hello from TypeScript + SCSS!"; document.body.appendChild(element); //# sourceMappingURL=my-library.mjs.map
Read Entire Article