Setting up a Stencil JS project with Tailwind CSS for beautiful Web components
Introduction
Stencil Js is a library for creating your own custom elements that work with most popular frameworks like React, Angular and Vue. This is a tutorial on how to set up Stencil JS with TailwindCSS.
Setup
Initialize a StencilJS project
npm init stencil
Choose component, name it and you’re good to go.
Next cd into your newly created directory and install
npm i
Install TailwindCSS and friends
Next, install all of these:
npm i -D @fullhuman/postcss-purgecss @stencil/postcss autoprefixer cssnano postcss-replace tailwindcss
Initialize a tailwind.config.js by running
npx tailwindcss init
Configure Stencil to use tailwind
Open up the stencil.config.ts and add imports like below (full configuration file here). We also define a purge function to keep only the classes used in each component.
Next, we add all these plugins. Note how we only use purge and cssnano in production since purge will slow down auto-reloading during development.
Run it!
And that’s about it! Your project will now be able to run tailwindcss.
Let’s go to src/components/my-component/my-component.css and add the following:
@tailwind base;@tailwind components;@tailwind utilities;
This will add the tailwind utilities to your component. You will have to do this for every component. You can also include custom utilities and use the @apply directives here. Although there are ways to inject global paths using PostCSS, it’s not working at the moment.
Let’s now start the development server
npm start
Now, in your src/components/my-component/my-component.tsx, try adding some classes
return <div class="text-purple-600">Hello, World! I'm {this.getText()}</div>;
You should see the results hot reloading (it might take some time to build in the first few loads, but it gets faster afterwards)
Hope that worked out for you.
Some issues
- The styles applied to the body are not shown in the web component (unless your web component has a body). I have started a discussion regarding transferring styles from the body element to the shadow DOM.
- The injectGlobalPaths of the PostCSS plugin seems to be broken and causes the whole app to crash. Will need to raise an issue there as well.
But this setup is workable. And in fact, the same CSS file can be used for multiple components as well in the styleUrl option. So, experiment and let me know if you’ve found a better way to use tailwind in your stencil project!