Adding css programatically via a module
I would like to add a couple lines of css via my module. What is the best approach here?
I thought I could do something like:
But that is failing with this when I run tests:
3 Replies
Hi @dmarr. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To programmatically add CSS via a Nuxt module, the recommended approach is to generate your CSS file as a template (using
addTemplate
) and then inject it into the global CSS array using the resolved path. You should not reference files inside .nuxt/
directly in the css
array, as Nuxt expects either a package name or a path relative to your project/module.
Here’s how you can do it:
1. Generate the CSS file as a template (using addTemplate
).
2. Push the resolved path of the generated template to nuxt.options.css
.
Here’s an example based on the official documentation:
Key points:
- Use the dst
property from the result of addTemplate
to get the correct path to the generated file.
- Do not reference .nuxt/assets/styles.css
directly in the css
array.
This approach is shown in the Nuxt documentation for injecting other assets, where a CSS file is added to the global CSS array using the resolved path from the module runtime, not a path inside .nuxt/
or a virtual path.
If you follow this pattern, your CSS will be correctly injected and available globally in your Nuxt app, and you should not encounter the "Invalid module" error.
For more details, see the official guide: Injecting Other Assets.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Woohoo