Nuptial Predicament Mediation

    yaml-to-js.macro

    0.2.0 • Public • Published

    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}
        - ${+ 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

    Install

    npm i yaml-to-js.macro

    DownloadsWeekly Downloads

    4

    Version

    0.2.0

    License

    MIT

    Unpacked Size

    135 kB

    Total Files

    7

    Last publish

    Collaborators

    • lorefnon