PostCSS plugin to transform environment variables in CSS.
Adds the ability to use a environment variables in CSS.
$ npm install postcss-envariables
Note: This project is compatible with node v6+
// 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
.
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');
}
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');
}