Babel macro to convert yaml template strings to javascript objects at build time.
Yaml is a terse and compact representation which makes writing large deeply nested data structures much more bearable than JSON or vanilla javascript.
It is especially well suited for configuration objects.
This plugin enables us to use inline yaml wherever we could use ordinary javascript objects, with zero additional run time overhead because the yaml expressions are transpiled to javascript objects at compile time (through a babel macro).
Given interpolation support, we can also construct objects having non serializable members like date, function etc. through yaml syntax.
From:
import yml from "yaml-to-js.macro"
const foo = yml`
config:
a: 10
b:
- 1
- 2
`;
To:
const foo = {
config: {
a: 10,
b: [1, 2]
}
}
There is a reasonable support for interpolated expressions:
From:
import yml from "yaml-to-js.macro"
const a = 10
const b = 20
const foo = yml`
config:
a: ${10}
b:
- ${a}
- ${a + b}
`;
To:
const a = 10
const b = 20
const foo = {
config: {
a: 10,
b: [a, a+b]
}
}
Note that when the interpolated expression is standalone, it will not be coerced as in the above example.
However if there are multiple interpolated expressions within the same member, they will coerced into a string:
const foo = yml`
config:
a: ${10} ${20}
`;
Results in:
const foo = {
config: {
a: `${10} ${20}`
}
}
If there are interpolations in property keys, they will be coerced to string template literals.
const foo = yml`
${10}:
a: 10
`
Results in:
const foo = {"10": {"a": 10}}
Interpolation support has well defined limits:
Note that because the interpolated expressions are retained in the generated code, it is not possible to compose yaml fragments together using interpolations.
So something like this will not behave as expected:
const somYamlStr = `
config:
- a
`
const foo = yml`${someYamlStr}`
It is better to use multiple macro invocations along with normal javascript object compositions:
const someObj = yml`{ prop1: "val1"}`
const someOtherObj = yml`{prop2: ${someObj}}`
Results in:
const someObj = { prop1: "val1" }
const someOtherObj = { prop2: someObj }
This macro relies on babel & babel-plugin-macros being configured properly.
If you are not familiar with babel, checkout the usage guide.
If you are not familiar with babel-plugin-macros, checkout the introduction and the installation section.
npm install --save-dev @babel/core babel-plugin-macros yaml-to-js.macro
In .babelrc
:
{
"plugins": ["babel-plugin-macros"]
}
Unsafe YAML features are disabled. Details.
Contributions are welcome in form of pull requests, bug reports.
There is no commercial support available for this product. I also don't accept donations.