The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country.

data = YAML.load(File.read('./src/constants/travel.yaml'))

data.fetch('countries').each do |key, value|
  File.open("./src/constants/countries/#{key}.yaml", 'w') { |file| file.write({ key => value }.to_yaml) }
end

The format of each individual file would resemble:

---
BA:
  sources:
    domestic:
    - Wearing masks and social distancing (a minimum of 2 metres) are [mandatory in
      all public places](https://www.oecd.org/south-east-europe/COVID-19-Crisis-in-Bosnia-and-Herzegovina.pdf).
    inbound:
    - The BiH Council of Ministers has announced that it will allow entry to the citizens
      of Croatia, Serbia, and Montenegro as of June 1, 2020. There is [still a ban
      to entry for non-resident foreign nationals.](https://ba.usembassy.gov/covid-19-information/)
    visa_quarantine:
    - Both the Republika Srpska and the Federation have [abolished self-isolation
      measures for people entering BiH.](https://ba.usembassy.gov/covid-19-information/).
  travel:
    domestic: partial
    inbound: partial
    inbound_allowed:
    - HR
    - RS
    - ME

Prior to splitting travel.yaml, it was consumed like this:

import TravelDefaults from '@/constants/travel.yaml';

export const Travel = TravelDefaults;

const { countries, checked_on } = Travel;

Now, the goal is to load all the separate YAML files simultaneously and consume them collectively (without individual imports). How can this be achieved in VUE using TypeScript?

Answer №1

const yaml = require('js-yaml');
const mergeYaml = require('merge-yaml');
const fs = require('fs');

const travelMerger = () => {
  const basePath = './src/constants/';

  const countryFiles = fs.readdirSync(`${basePath}countries/`);

  const filesWithDir = countryFiles.map((file) => `${basePath}countries/${file}`);

  const countriesYaml = mergeYaml(filesWithDir);

  const yamlStr = yaml.safeDump(countriesYaml);

  fs.writeFileSync(`${basePath}travelMerged.yaml`, yamlStr, 'utf8');
};

module.exports = travelMerger;

Although this code works perfectly fine, it is not compatible with Vue when using TypeScript.

Answer №2

If you're looking for a solution that is static at compile-time, you can achieve it by utilizing webpack's require.context feature (docs) along with a yaml loader.

Illustration

Using the vue-cli-plugin-yaml.

In this scenario, suppose your yml files are stored in src/constants/countries/*.yml, you can utilize the below code snippet to access each JS object from the yaml files through a computed method named countries:

<template>
  <div id="app">
    <div
      v-for="country in countries"
      :key="country.key"
      class="country"
    >
      <h1>{{country.key}}</h1>
      <hr />
      <h2>{{country.sources.domestic[0]}}</h2>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue } from 'vue-property-decorator'
export default class App extends Vue {
  get countries () {
    const requireContext = require.context(
      './constants/countries',
      true,
      /(.*)\.yml/
    )
    return requireContext.keys().map((fileName) => {
      const key: string = fileName.split('.')[1].replace('/', '')
      return {
        key: key,
        ...requireContext(fileName)[key]
      }
    })
  }
}
</script>

<style>
#app {
  text-align: center;
  margin-top: 60px;
}
.country{
  border:1px solid black;
  margin:20px;
}
</style>

illustrative example featuring dummy files

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing GetServerSideProps with Next-Auth: Error message - Trying to destructure property 'nextauth' from 'req.query' which is undefined

I encountered an issue while using the getServerSideProps function in Next.js with Next-Auth. The error I received was a TypeError: TypeError: Cannot destructure property 'nextauth' of 'req.query' as it is undefined. Upon checking with ...

How to Enhance Angular ui-router nested views with Resolve?

I have been working on creating a customized version of my Angular 1.4.12 application with nested views. The main purpose behind this customization is to accommodate sections within the app that require a header/content/footer structure, while others do no ...

Guide to Displaying HTTP POST Request Response on Pug Template

Whenever a user interacts with the form, I initiate an HTTP POST request to the database server. Subsequently, the database server sends a POST request back to the user's server. The issue I am facing is the inability to display this database result ...

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Managing touchEvents in Vue: A comprehensive guide

Is it possible to manage touch events in Vue3 without using an external library? I am trying to make an element draggable (drag and drop to another location) with touch input. The elements are generated using v-for. I was able to implement mouse control w ...

How to modify the color of a div element with jQuery?

I need some help changing the color of a div with 'jQuery', but I am not sure how to do it. Below is the code I have been trying: function updateDivColor() { $('#OutlineX1').css("color","blue"); } ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

Exploring Typescript: Uncovering the Secrets of the navigator.connection Property

I am trying to access the NetworkInformation interface by using a simple TypeScript function like the one shown below: private checkNetworkConnection(): void { const connection = Navigator.connection || navigator.mozConnection || navigator.webkitConn ...

Issue with CSRF Token discrepancy between cookies and HTML

Is there a proper way to retrieve the CSRF Token? In my Vue SPA, I am using Axios for login. I have converted everything to Vue components except for the Routes generated by `php artisan ui:auth`, so now I cannot use `@csrf` on my forms and have to send t ...

When it comes to TypeScript, it feels like my interface can accept anything I throw at it, and it struggles to grasp how I've implemented and imported redux-toolkit and styled components

My Current Struggle: Errors in Typescript are occurring seemingly at random. The interface in my index.tsx file doesn't align with the object it should describe, yet no red flags are raised. On top of that: An error pops up when attempting to import ...

The results from utilizing Mongoose's text search feature are inaccurate and not matching the expected

Currently, I am in the process of developing a recipe blog website using Mongoose, Node.js, and Express. However, I have encountered an issue with the text search functionality not producing the desired output. In my Recipe.js schema, I have included spec ...

utilizing regular expressions to retrieve data

I am facing a challenge in extracting both the product name and price from the given data. The desired result, which includes both the product name and price, is not on the same line. How can I include the line that comes before the price as well? Here is ...

Challenges in managing click events

I am facing an issue with my Jquery UI resize handler. It is positioned absolutely over a div that contains a set of LI's (in this case, a set of dates). The problem is that when I click on any date, the click event is not being propagated because the ...

Sending data to child components in Ionic

I am currently utilizing Ionic's router-outlet to navigate between a parent page and three children pages: parent.page.html <ion-content> <ion-router-outlet></ion-router-outlet> </ion-content> parent-routing-module.page.t ...

What will be the quickest and most reliable trigger - matchMedia, window.resize, orientationchange, or perhaps both combined?

I am trying to trigger a function when a user rotates their device and I'm seeking advice on which event would be most effective for this purpose. In your experience, which event do you recommend that will call the function quickly and consistently? I ...

Ways to access a nested property within an array

I'm having an issue when trying to access a sub property of an array. Here's the snippet in question: ngOnInit() { this.menus = this.navService.defaultMenu; console.log(this.getMenusItem()); this.registerChangeInProjects(); } T ...

Show or hide a specific element based on the property assigned to a user's role

In my current project, I am focusing on distinguishing between two key user roles: editor and guest. The editor holds complete privileges for create, read, update, and delete operations, while the guest is limited to viewing certain elements like a list ...

Another project cannot import the library that was constructed

I am in the process of creating a library that acts as a wrapper for a soap API. The layout of the library is structured like this: |-node_modules | |-src | |-soapWrapperLibrary.ts | |-soapLibraryClient.ts | |-types | |-soapResponseType.d.ts The libra ...

Exploring the world of unit testing in aws-cdk using TypeScript

Being a newcomer to aws-cdk, I have recently put together a stack consisting of a kinesis firehose, elastic search, lambda, S3 bucket, and various roles as needed. Now, my next step is to test my code locally. While I found some sample codes, they did not ...

Utilizing Vue's data binding feature with an array

Hey, I'm trying to send an array to another component like this: <paystack :amount="parseFloat(props.item.amount)" :email="$store.state.email" :reference="reference" :callback="callback" ...