How to Configure Tailwind for Component Previews and Apps

ig
ignacioaldama11 months ago

In a previous blog, the Tailwind Webpack Transformer was introduced as a way to provide support for Tailwind component previews and apps.

In this blog post, we'll take a look at how to extend your Tailwind CSS with plugins, and how to configure it to work with different frameworks.

Tailwind CSS can only be customized when the CDN option is turned off (tailwindTransformer({ cdn: false })).

Change the default Tailwind config

Fork the default Tailwind config component into your workspace:

$bit
Copiedcopy

Follow the next sections to learn how to configure it and use it for your components preview and apps.

Include new component files

The Tailwind PostCSS plugin, injected by this Tailwind Webpack Transformer, scans the components' files, looking for Tailwind classes (to generate). It does that by first receiving a list of file patterns to scan.

Depending on the tools and frameworks you use, you might want to change the file patterns to scan.

Change the value of the content variable, it the preset.ts file, to include the files you want to scan.

For example, the following will include *.vue files (in your components):

const content = globSync(['**/*.{vue}'], {
  ignore: ['**/node_modules/**'],
});
CopiedCopy

Extend Tailwind with plugins

Head over to the tailwind.config.js file, of your forked Tailwind config component, and add the plugins you want to use.

For example, the following adds the 'typography' plugin:

import bitPreset from './preset';

/** @type {import('tailwindcss').Config} */
export default {
  // use the basic preset to get the files from the workspace
  content: [...bitPreset.content],
  theme: {
    extend: {},
  },
  plugins: [
    require('@tailwindcss/typography'),
  ],
};
CopiedCopy

Bit automatically detects your Tailwind config component has a new dependency (the plugin).

Run the following command to install the latest version of any missing dependency:

$bit
Copiedcopy

Use your custom Tailwind config

Head over to your env's preview method or app plugin file, and pass your custom Tailwind config:

/* @filename: my-env.env.ts */

// ...
import { Preview } from '@teambit/preview';
import { tailwindTransformer } from '@learnbit/styling.transformers.tailwind';
import myCustomTailwindConfig from '@my-org/my-scope.config.tailwind';

export class MyEnv extends ReactEnv {

  preview(): EnvHandler<Preview> {
    return ReactPreview.from({
      mounter: require.resolve('./preview/mounter'),
      transformers: [
        tailwindTransformer({
          config: myCustomTailwindConfig;
        }),
      ],
    });
  }
}

export default new MyEnv();
CopiedCopy