DEV Community

Discussion on: Create a Component Library Fast🚀(using Vite's library mode)

Collapse
 
headwinds profile image
brandon flowers • Edited

This is a fantastic article and gave me the confidence to rebuild my personal component library, cross-country, with vite and upgrade to storybook 7!

I also wanted to consume the library in a NextJS app but instead of separating the CSS and JS, I wanted to compile them into a single JS file which also eliminates the global import css error and in theory one wouldn't have to worry importing any third-party css into the _app file.


NextJS Update
I'm now using this recommended rollup-plugin-css-only approach, and have decided that I'm ok with including simple instructions to simply import the single bundled css file into the NextJS _app.js file since you only have to do this once.


Instead of vite-plugin-lib-inject-css, I'm experimenting with vite-plugin-css-injected-by-js which seems to be what I want but isn't quite working yet. While I have no css errors I still don't see the css being applied when I consume the published library components. They appear unstyled which definitely isn't good. This is the recommended setup:

When I try vite-plugin-lib-inject-css with my library, publish it, and then consume it in a non-nextjs app like the Vite react stackblitz example, it works! I can import my components and their css style is maintained.

This is the ChatGPT explanation:

The vite-plugin-css-injected-by-js and vite-plugin-lib-inject-css are both Vite plugins that help manage CSS in your JavaScript bundles, but they serve slightly different purposes and work in different ways.

The vite-plugin-css-injected-by-js takes all the CSS generated by the build process and adds it via JavaScript. This results in a single JavaScript file, as the CSS file is not generated separately. This plugin is useful for those who want a single JavaScript file and can be configured to execute the CSS injection before or after your app code

On the other hand, vite-plugin-lib-inject-css is designed to work specifically in library mode. It injects CSS at the top of each chunk file using an import statement. This plugin supports multi-entries build and is especially helpful when building component libraries

Collapse
 
receter profile image
Andreas Riedmüller

Hm, I think injecting css has it's own problems like no control over the order of appearance. Also no further CSS processing is possible downstream... But this might be no problem in you use case.

What do you mean with "you don't have to worry importing any third-party css into the _app file."?