Skip to content

Webpack loader which loads Nunjucks-templated YAML file and returns a function that creates a JavaScript object

License

Notifications You must be signed in to change notification settings

aapf/yaml-nunjucks-loader

Repository files navigation

yaml-nunjucks-loader

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.

Prerequisites

Installation

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

Usage

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']
      }
    ]
  }
}

Nunjucks Configuration

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 &lt;. You can change this behaviour by setting autoescape to true.

Examples

Limitations

About

Webpack loader which loads Nunjucks-templated YAML file and returns a function that creates a JavaScript object

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published