Tailwind not being applied to library

Viewed 1063

I have created a library in angular which is styled using tailwind. This is then been push to NPM and then imported into a new project, but the css is not getting applied. I have referenced the node-module path in my tailwind.config.ts:

    content: [
    "./src/**/*.{html,ts}",
    './node_modules/components-name/**/*.{html,js,ts}'
  ],

What am i missing?

Tailwind is working if i apply it directly to the new application, it just doesn't work with the imported library.

1 Answers

If you expect all depender apps to utilize tailwind, you can use classes in your library and have them configure a content path of ./node_modules/my-lib/esm2020/**/*.mjs. It does find the inlined/escaped classes in the Ivy compiled files. esm2020 to scope the scan.


If you want applications to use it without tailwind as a dependency, you can compile the styles and provide the utility classes in a css file.

I suggest creating a tailwind.config.js under your library and scope it's configuration to only pick up classes/styles found, also turning off preflight as to not produce conflicting styles to applications pulling in your library's styles. Only needed if you have other apps in this project (such as a demo/playground) that'll cause tailwind to bring in excess utility classes. If you have extentions/customizations, you might create a 3rd file and share the configs between them.

projects/my-lib/tailwind.config.js

module.exports = {
  prefix: '',
  content: [
    './projects/my-lib/**/*.{html,ts,css,scss}',
  ],
  darkMode: 'class',
  theme: {
    extend: {
    },
  },
  variants: {
    extend: {
    },
  },
  plugins: [],
  corePlugins: {
    preflight: false,
  }
};

Note the content path is still relative from project root as that's the context it's ran at

I recommend adding a stylesheet to use, even if it only contains @tailwind utilities;, otherwise it'll potentially include bad root variables.

projects/my-lib/style.scss

@tailwind utilities;

Then add a postbuild to your top-level package.json to produce the stylesheet, provided you use npm run build to build the library.

    "postbuild": "npx tailwind -c projects/my-lib/tailwind.config.js -i projects/my-lib/style.scss -o dist/my-lib/style.css",

Direct depender projects to then include this compiled stylesheet:

@import 'my-lib/style.css'

Downsides are you get all utility classes from all components, even if they're unused (same happens for projects using tailwind, so not so bad. Also the depender project may produce duplicate utility classes if using tailwind itself, but I'd hope they're using postcss and autoprefixer :)

Plus side is your library doesn't require the depender to have tailwind (unless using some utilities that depend on css vars...). Might be worth experimenting with providing the base of tailwind along as well, just not the reset (preflight).

Note that both options will not work with @apply functionality.

Related