postcss-envariables

1.0.0 • Public • Published

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');
}

Dependents (0)

Package Sidebar

Install

npm i postcss-envariables

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

8.88 kB

Total Files

5

Last publish

Collaborators

  • scrum