Skip to content

Instantly share code, notes, and snippets.

@mikeyamadeo
Last active August 10, 2016 17:23
Show Gist options
  • Save mikeyamadeo/c2b9b3f541d34399483fefb020e1046d to your computer and use it in GitHub Desktop.
Save mikeyamadeo/c2b9b3f541d34399483fefb020e1046d to your computer and use it in GitHub Desktop.
// src/App/style/settings
export const colors = {
primary: 'red'
}
// post-css-plugins/settings-from-js.js
var postcss = require('postcss')
var settings = require('./src/App/style/settings')
module.exports = postcss.plugin('settings-from-js', function (opts) {
/**
* 1. Using walkRules() iterates through every rule in your CSS;
* a rule is basically your selector and the styles you’ve set between its curly braces.
* 2. walkDecls() iterates through every declaration;
* a declaration is essentially each line in the style. (e.g. color: var(colors.primary))
* 3. Check to see if the declaration has a variable in it.
* 4. if the syntax is color: var(colors.primary), you'll do some string manipulation to get everything between the parens
* 5. do something like variableName.split('.') -> ['colors', 'primary'] -> settings[arr[0]][arr[1]] (iteratively)
* 6. change `color: var(colors.primary)` to `color: variableValue`
*/
return function (css, result) {
css.walkRules(function (rule) { /* [1] */
rule.walkDecls(function (decl, i) {
if (decl.indexOf('var(') !== -1) {
var variableName = extractVariableName(decl) /* [4] */
var variableValue = extractVariableValue(variableName) /* [5] */
var newDeclValue = replaceVarValue(decl, variableValue) /* [6] */
decl.value = newDeclValue
}
})
})
}
})
// webpack.config.js
module.exports = {
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader!postcss-loader"
}
]
},
// 1. add it to postcss transforms in webpack
postcss: function () {
return [
require('autoprefixer'),
require('./post-css-plugins/settings-from-js') /* [1] */
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment