How to split generated CSS code form Tailwind?

Viewed 3008

I am looking for a solution to split the big CSS file generated by Tailwind PostCSS plugin (combined with purgecss plugin) into multiple CSS files (one CSS file per consumer JS file). Consumed CSS rules by JS files can be detected by looking into used selectors in JS files (i.e. class names such as p-1 and m-1).

Any idea how to achieve this or something similar?

1 Answers

I was partially able to solve this.

First of all, remove all tailwind code from postcss.config.js. Then create tailwind.config.js in the folder with the file, that is using tailwind classes.

Here's my basic demo example.

In the folder there are two files:

App.vue
tailwind.config.js

App.vue:

<template>
  <div
    id="app"
    class="flex flex-col flex-no-wrap items-center content-center justify-center"
  >
    {{ message }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "I'm from vue file"
    };
  }
};
</script>

<style lang="scss">
@import "scss/dynamic/tailwind.scss";

#app {
  color: $red;
}
</style>

scss/dynamic/tailwind.scss (to have easy acces to tailwind in any file):

@tailwind components;
@tailwind utilities;

tailwind.config.js:

module.exports = {
  purge: {
    mode: "all",
    content: [__dirname + "/App.vue"]
  },
  theme: {},
  variants: {},
  plugins: []
};

webpack.config.js (only css part):

...
{
  test: /\.(sa|sc|c)ss$/,
  use: [
    MiniCssExtractPlugin.loader,
    "css-loader",
    {
      loader: "postcss-loader",
      options: {
        plugins: env => {
          const dir = env._module.context;
          const config = dir + "/tailwind.config.js";

          return fs.existsSync(config)
            ? [require("tailwindcss")(config)]
            : [];
        }
      }
    },
    {
      loader: "sass-loader",
      options: {
        data: `@import "scss/static/abstracts";`
      }
    }
  ]
}
...

In the end I have a css file, that is loaded dynamically, and looks like this:

.flex{display:flex}.flex-col{flex-direction:column}.flex-no-wrap{flex-wrap:nowrap}.items-center{align-items:center}.justify-center{justify-content:center}.content-center{align-content:center}#app{color:red}

Problems, that I still have:

  • If multiple files (that are loaded dynamically on one page) use same classes, css code is repeated
  • I need to have multiple config files + only one config file per folder.
  • The config file for main app.scss doesn't see classes in .blade.php files, maybe it has something to do with the files path:
const path = require("path");

module.exports = {
  purge: [
    path.resolve("../../../../views/base.blade.php"),
    path.resolve("../../../../views/page/home.blade.php")
  ],
  theme: {},
  variants: {},
  plugins: []
};
Related