Replace Variable

Replace Variable

yarn add @elodin/plugin-replace-variable

The replace variable plugin is used to replace dynamic variables with static values before compilation in order to get rid of runtime code.
It can be used to achieve e.g. static theming.

Usage

To use the plugin, simply add it to your Elodin configuration and you're ready to go.

elodin.config.js

var replaceVariable = require('@elodin/plugin-replace-variable')
module.exports = {
plugins: [
replaceVariable({
variables: {
primaryColor: 'red',
secondaryColor: 'blue',
},
}),
],
}

Configuration

OptionTypeDefaultDescription
variablesObject{}The variable map which are used to replace values
selectorFunction(vars, prop) => vars[prop]A property selector function

Example

Given the variables from the usage example above:

button.elo

(Input)

style Button {
backgroundColor: $primaryColor
color: $secondaryColor
}

button.elo

(Output)

style Button {
backgroundColor: red
color: blue
}

Custom selector

Apart from plain flat variables, we can also use a custom selector to implement more complex structures.

elodin.config.js

var replaceVariable = require('@elodin/plugin-replace-variable')
module.exports = {
plugins: [
replaceVariable({
selector: (vars, prop) =>
prop
.split('_')
.reduce((out, sub) => (out ? out[sub] : undefined), vars),
variables: {
theme: {
colors: {
primary: 'red',
secondary: 'blue',
},
sizes: {
l: 20,
m: 16,
s: 12,
},
},
},
}),
],
}

Example

button.elo

(Input)

style Button {
backgroundColor: $theme_colors_primary
color: $theme_colors_secondary
fontSize: $theme_sizes_l
}

button.elo

(Output)

style Button {
backgroundColor: red
color: blue
fontSize: 20
}