postcss-lit

Lit support for PostCSS and related tooling

Usage no npm install needed!

<script type="module">
  import postcssLit from 'https://cdn.skypack.dev/postcss-lit';
</script>

README

postcss-lit

A PostCSS and stylelint custom syntax for parsing CSS inside lit templates.

For example:

class MyElement extends LitElement {
  static styles = css`
    .foo { color: hotpink; }
  `;
}

Install

npm i -D postcss-lit

Usage with PostCSS

In your postcss.config.js:

module.exports = {
  syntax: 'postcss-lit',
  plugins: [...]
};

PostCSS with webpack

If you use webpack to execute postcss, you must ensure the right order of loaders, like so:

module.exports = {
  entry: './src/my-element.ts',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: ['postcss-loader', 'ts-loader'],
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.ts']
  },
  output: {
    filename: 'bundle.js'
  }
};

This is important as postcss will transform your CSS before typescript transpiles to JS (which is what you want to happen).

Usage with stylelint

In your .stylelintrc.json (or other stylelint config file):

{
  "customSyntax": "postcss-lit"
}

Or with the CLI:

stylelint --custom-syntax postcss-lit

Usage with vscode-stylelint

In order to make the vscode-stylelint extension work with this syntax correctly, you must configure it to validate JS and/or TypeScript files.

You can do this by following these instructions.

For example:

{
  "stylelint.validate": ["css", "javascript", "typescript"]
}

Usage with tailwind

In your postcss.config.js:

module.exports = {
  syntax: 'postcss-lit',
  plugins: {
    tailwindcss: {}
  }
};

In your tailwind.config.js:

const {tailwindTransform} = require('postcss-lit');

module.exports = {
  content: {
    files: ['./src/**/*.ts'],
    transform: {
      ts: tailwindTransform
    }
  }
};

You may then use tailwind's directives and classes in your elements:

class MyElement extends LitElement {
  static styles = css`
    @tailwind base;
    @tailwind utilities;
  `;

  render() {
    return html`
      <div class="text-xs">Small text</div>
    `;
  }
}

You must specify all tailwind directives you intend to use in your CSS, otherwise their replacement CSS will be incorrectly appended to the end of the document.

For example, in the code above, @tailwind base and @tailwind utilities were specified to make text-xs available. Without them, the code would not build.

Tailwind with webpack

See the same advice as with postcss standalone, here.