Create separate CSS files in postcss & rollup
Asked Answered
S

3

8

I want each css file I import in my JS to create a new css file for my build. For instance:

import "./app.css";
import "./admin.css";

would create dist/app.css and dist/admin.css. I am using rollup and here is my config file:

import commonjs from "@rollup/plugin-commonjs";
import postcss from "rollup-plugin-postcss";
import resolve from "@rollup/plugin-node-resolve";
import { terser } from "rollup-plugin-terser";

import postcssImport from "postcss-import";
import postcssNested from "postcss-nested";
import autoprefixer from "autoprefixer";

const dev = process.env.WP_ENV === "development";

export default {
  input: "src/main.js",
  output: {
    sourcemap: dev,
    format: "iife",
    name: "main",
    file: "dist/main.bundle.js",
  },
  plugins: [
    resolve({
      browser: true,
    }),
    postcss({
      plugins: [postcssImport(), postcssNested(), autoprefixer()],
      extract: true,
      sourceMap: "inline",
      minimize: !dev,
    }),
    commonjs(),
    !dev && terser(),
  ],
  watch: {
    clearScreen: false,
  },
};

Sylphid answered 18/12, 2020 at 23:2 Comment(1)
I would be very much interested in the answer as well...Truesdale
O
7

It has not been documented but you can use include, exclude according to their source code.

An example here for two css files:

import { resolve } from "path"
plugins: [
  postcss({
    include: "**/admin.css",
    extract: resolve('dist/admin.css')
  }),
  postcss({
    include: "**/app.css",
    extract: resolve('dist/app.css')
  })
]

And if you want to exclude one file:

plugins: [
  postcss({
    exclude: "**/bootstrap.css",
    extract: resolve('dist/app.css')
  }),
  postcss({
    include: "**/bootstrap.css",
    extract: resolve('dist/bootstrap.css')
  })
]
Ontina answered 4/3, 2021 at 16:17 Comment(1)
It doesn't work for me. Rollup is 1.32.1.Saberio
V
5

I created a plugin - rollup-plugin-lib-style that generates CSS separately for every style file and imports these generated CSS files (as CSS modules).

Vestal answered 28/10, 2022 at 12:25 Comment(0)
S
1

This is what I ended up with

import resolve from "@rollup/plugin-node-resolve";
plugins: [
  external(),
  resolve(),
  commonjs(),
  typescript(),
  postcss({
    include: "src/index.css",
    extract: "index.css",
    minimize: true,
    sourceMap: true,
  }),
  postcss({
    include: "src/themes/file2.css",
    extract: "themes/file2.css",
    minimize: true,
    sourceMap: true,
  }),
  terser(),
]
Septal answered 29/8, 2022 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.