1.0.0 • Published 5 years ago

postcss-envariables v1.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

postcss-envariables

PostCSS plugin to transform environment variables in CSS.

Travis Build StatusAppVeyor Build Statusnodenpm versionDependency StatusXO code styleCoveralls status

npm downloadsnpm

Why?

Adds the ability to use a environment variables in CSS.

Install

$ npm install postcss-envariables

Note: This project is compatible with node v6+

Usage

// Dependencies
import fs from 'fs';
import postcss from 'postcss';
import env from 'postcss-envariables';
import cssVariables from 'postcss-css-variables';

// CSS to be processed
const css = fs.readFileSync('css/input.css', 'utf8');

// Process CSS
const output = postcss()
    .use(env({ /* env: { contextPath: path/to/file } */ }))
    .use(cssVariables())
    .css;

console.log(output);

Use before plugin postcss-css-variables.

Example

Node

import fs from 'fs';
import postcss from 'postcss';
import env from 'postcss-envariables';
import cssVariables from 'postcss-css-variables';

const css = fs.readFileSync('css/input.css', 'utf8');

// Process CSS
const output = postcss()
    .use(env({ env: { contextPath: 'dev' } }))
    .use(cssVariables())
    .css;
/* input.css */
:root {
    --contextPath: env.contextPath;
}

.selector {
    backgrount-image: url('var(--contextPath)/image.png');
}
/* Output example */
.selector {
    backgrount-image: url('dev/image.png');
}

Webpack

package.json

"scripts": {
    "build": "webpack --mode=development"
}

postcss.config.js

module.exports = ({options: {env}}) => {
  return {
    plugins: {
      'postcss-envariables': {
        env: {
          contextPath: env === 'development' ? 'dev' : ''
        }
      },
      'postcss-css-variables': {}
    }
  }
};

webpack.config.js

module.exports = (env, argv) => ({
  mode: env,
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: 'postcss-loader',
            options: {
              config: {
                ctx: {
                  env: argv.mode
                }
              }
            }
          }
        ]
      }
    ]
  }
});

input.css

:root {
    --contextPath: env.contextPath;
}

.selector {
    backgrount-image: url('var(--contextPath)/image.png');
}

Output

.selector {
    backgrount-image: url('dev/image.png');
}