David Lozzi
David Lozzi

Reputation: 15875

Export my CSS vars with my module using rollup?

I have a little module that I am sharing across a few projects. It is successfully exporting components, but now I'd like to get my global style vars, like $contoso-primary: #ff0000 to be exported as well so we can start sharing CSS vars in my consuming app, like background-color: $contoso-primary. I'm using the rollup.js, is this possible with this library or with its plugins? If so, what plugin am I looking for? I've tried postcss already but doesn't appear to work unless I'm missing something.


export default {
  input: 'src/index.js',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'es',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({
      extract: true
    }),
    url(),
    svgr(),
    babel({
      exclude: 'node_modules/**'
    }),
    resolve(),
    commonjs()
  ],
  onwarn(warning, warn) {
    if (
      warning.code === 'CIRCULAR_DEPENDENCY'
      && warning.importer.indexOf('node_modules/semantic-ui-react') > -1
    ) return;
    warn(warning);
  }
};

my scss file that has my vars looks something like:

$primary: #177757,
$secondary: #D50000

and in the consuming project I'd like to refer to these in my scss files like:

.button {
  background: $primary
}

I can't get an .css file into my dist folder, and the documenation on rollup-plugin-postcss is a little light.

Upvotes: 0

Views: 2341

Answers (2)

johnjohn
johnjohn

Reputation: 1094

I was able to make this work by duplicating the variable declarations in both the postcss.config.js and rollup.config.js

Rollup config:

import postcss from "rollup-plugin-postcss";
import postcssSimpleVars from "postcss-simple-vars";
const variables = require("./pathTo/variableConfig.js");
...
const config = {
...
plugins: [
  postcss({
    postcssSimpleVars({
      variables: function () {
         return variables;
      }
    }),
  })
]

postCSS config:

const variables = require("./variableConfig.js");

plugins: [
 ...
  require("postcss-simple-vars")({
    variables: variables
  })
]

variableConfig.js:

const baseDir = "../src/utils/constants";
const { COLORS } = require(`${baseDir}/colors`);
const { MQ } = require(`${baseDir}/mediaQueries`);
const { BREAKPOINTS } = require(`${baseDir}/breakpoints`);

const cssVars = Object.assign(COLORS, MQ, BREAKPOINTS);

module.exports = cssVars;

Upvotes: 0

Sunil Kashyap
Sunil Kashyap

Reputation: 2984

postcss-simple-var this plugin will able to share sass like variables.

plugins:  [
      postcss({
        plugins: [
          simplevars()
        ],
      extensions: [ '.css' ],
    }),
    ...
  ]

for more information read this article.

Upvotes: 1

Related Questions