HCL v2 Parser for JavaScript

1.0.1 · active · verified Tue Apr 21

This library provides a JavaScript parser for HCL (HashiCorp Configuration Language) version 2 syntax. It is currently at version 1.0.1 and appears to be actively maintained, being an updated fork of an unmaintained predecessor (`hcl2-parser`). Its key differentiator is robust support for HCL v2, which many other JavaScript parsers lack. It achieves this by wrapping the Go-based `tmccombs/hcl2json` library, transpiling the Go code to JavaScript using GopherJS. Unlike its unmaintained predecessor, this version correctly returns parsing errors to the user by rejecting a Promise, making it more reliable for production use cases like parsing Terraform configurations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse an HCL string into both a JSON string and a JavaScript object, including basic error handling for invalid HCL syntax.

import { parseToObject, parseToString } from 'hcl2-json-parser';

const hclString = `
# Create a resource group
variable "azureRegion" {
  type = string
  default = "uksouth"
}
resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = var.azureRegion
}
`;

async function parseHCL() {
  try {
    // Parse into a JSON string
    const stringResult = await parseToString(hclString);
    console.log("Parsed JSON String:\n", stringResult);

    // Parse into an object
    const objectResult: any = await parseToObject(hclString);
    console.log("\nResource Group Name:", objectResult.resource.azurerm_resource_group.example.name);
    console.log("Resource Group Location:", objectResult.resource.azurerm_resource_group.example.location);

    // Demonstrate error handling for invalid HCL
    await parseToObject("invalid hcl!!!");
  } catch (e: any) {
    console.error("\nError parsing HCL (expected for 'invalid hcl!!!'):", e.message);
  }
}

parseHCL();

view raw JSON →