JSPM

yaml-to-js.macro

0.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q17582F
  • License MIT

babel macro for converting yaml to js

Package Exports

  • yaml-to-js.macro

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (yaml-to-js.macro) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

yaml-to-js.macro

Babel macro to convert yaml template strings to javascript objects at build time.

code style: prettier License: MIT

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 in the same phrase, 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 }

Installation

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.

tl;dr

npm install --save-dev @babel/core babel-plugin-macros yaml-to-js.macro

In .babelrc:

{
    "plugins": ["babel-plugin-macros"]
}

Support for interpolated expressions