Webpack loader which loads Nunjucks-templated YAML file and returns a function that creates a JavaScript object
MIT License
yaml-nunjucks-loader is an Webpack loader which loads Nunjucks-templated YAML file and returns a function that creates a JavaScript object with given parameters.
Template files are compiled to JavaScript and embedded into a bundle. Applying parameters and parsing YAML are executed at runtime.
yaml-nunjucks-loader requires yaml and Nunjucks.
Install required libraries to your project:
npm install --save yaml nunjucks
Install yaml-nunjucks-loader:
npm install --save-dev yaml-nunjucks-loader
If you use Yarn, execute the following instead:
yarn add yaml nunjucks
yarn add --dev yaml-nunjucks-loader
Webpack configuration:
{
// ...
modules: {
rules: [
// ...
{ tests: /\.yaml$/, loader: 'yaml-nunjucks-loader' }
]
}
}
YAML template pod.yaml
:
apiVersion: v1
kind: Pod
metadata:
name: {{ name }}
spec:
containers:
- name: ubuntu
image: ubuntu:trusty
imagePullPolicy: IfNotPresent
command: ['sleep']
args: ['{{ sleep }}']
name
will be filled at runtime.
JavaScript code:
import podTemplate from './pod.yaml'
const podManifest = podTemplate({ name: 'example', sleep: 600 })
console.log(podManifest)
podManifest
is an Object as follows:
{
apiVersion: 'v1',
kind: 'Pod',
metadata: {
name: 'example'
},
spec: {
containers: [
{
name: 'ubuntu',
image: 'ubuntu:trusty',
imagePullPolicy: 'IfNotPresent',
command: ['sleep'],
args: ['600']
}
]
}
}
You can pass Nunjucks configuration options as a JSON query parameter.
Example:
{
// ...
modules: {
rules: [
// ...
{ tests: /\.yaml$/, loader: 'yaml-nunjucks-loader?{nunjucks:{autoescape:true}}' }
]
}
}
examples/react-app uses the above configuration.
Since Nunjucks is used to render YAML instead of HTML, autoescape
is by default false
. <
will not be converted to <
. You can change this behaviour by setting autoescape
to true
.