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

Is there a way to create a "navigate to" button directly from the text within a <p> element?

Within my HTML, there is a <p> tag which dynamically receives a link value from a JavaScript function. The link could be anything from www.google.com to youtube or instagram. How can I utilize the "copytoclipboard" library to copy this link to clipbo ...

Having trouble with your React/TypeScript/Redux/Thunk action not dispatching and the state remaining unchanged?

Currently, I am facing an issue while attempting to send a GET request to an API using React-Redux & TypeScript. The goal is to dispatch an action upon clicking a button (onClick event), make the request, update the state via the reducer, and finally log t ...

React - Can you explain the purpose of the callback function in the forceUpdate method?

The React documentation mentions that the forceUpdate method includes a parameter called callback. Does this function in any way resemble the second parameter found in setState, which is executed after setting state? Or does it serve a different purpose? ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Having Trouble Finding Vue Component Definition Using Vite Alias in Import Path

When I click on the Component within the code snippet: import Component from '@/components/Component.vue'; I am unable to navigate to its definition when using vite alias. Seeking a potential solution. ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

Struggling to make jQuery code function in an external file without causing clashes with additional jQuery code

When incorporating this simple code into its own separate file, I encounter some jQuery conflicts with another piece of code. jQuery(function ($) { $(".tabContents").hide(); $(".tabContents:first").show(); $("#tabContainer ul li a").click(fun ...

ConcatMap in RxJS processes only the last item in the queue

Currently, I am implementing NGRX with RXJS. Within the effects layer, I am utilizing a concatMap to organize my requests in a queue fashion. However, once the latest request is finished, I aim to execute the most recent item added to the queue instead of ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

JavaScript SQL results in either a string or an object after executing a

I am facing an issue with the following query: sql = client.query("SELECT * FROM monitormaterialsept", function (err, result, fields) { if (err) throw err; console.log(result); }) I am unsure of what the output of the sql variable is. Is there a ...

unable to reinstall due to removal of global typing

After globally installing Moment typing with the command typings install dt~moment --save --global Checking the installed typings using typings list shows: ├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93fffcf7f2e0 ...

Can JavaScript's Gamepad API be used to register a custom game controller?

Background Story Working on a virtual reality app with A-frame to showcase VR gadgets. Custom controllers connect via websocket/bluetooth and we want them compatible with tracked-controls. These components use Gamepad API for model positioning and are fri ...

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

The Facebook Like Button appears on Firefox but not on Internet Explorer due to Javascript errors

Hello everyone, I could really use some help with an issue I am facing. My Facebook like button works perfectly fine in Firefox, but when it comes to Internet Explorer, I keep encountering Javascript errors and the button doesn't show up at all: If y ...