【问题标题】:How to load multiple YAML files at once in JavaScript如何在 JavaScript 中一次加载多个 YAML 文件
【发布时间】:2020-12-07 06:45:51
【问题描述】:

我编写了一个 Ruby 脚本,它将一个包含国家/地区键和信息列表的大型 YAML 文件(称为 travel.yaml)拆分为每个国家/地区的单独文件。

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

使每个文件看起来像这样:

---
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

在拆分travel.yaml之前,是这样消费的:

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

export const Travel = TravelDefaults;

const { countries, checked_on } = Travel;

我现在想一次加载所有单独的 YAML 文件并使用它们(无需单独导入每个文件)。

我该怎么做?这必须在 VUE 和 Typescript 中完成。

【问题讨论】:

  • 你可以将它们合并成一个大的 YAML 文件(称为travel.yaml

标签: javascript typescript vue.js yaml


【解决方案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;

这可行,但不幸的是,在带有 TypeScript 的 Vue 中不行。

【讨论】:

    【解决方案2】:

    如果您不介意编译时静态解决方案, 你可以使用 webpack require.context (docs) 和 yaml 加载器来完成。

    示例

    使用vue-cli-plugin-yaml

    假设你的 yml 文件位于src/constants/countries/*.yml 您可以使用以下代码使用名为countries 的计算方法从 yaml 文件中获取每个 JS 对象:

    <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>
    

    example with some dummy files

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 2016-10-05
      • 2016-10-24
      • 2018-06-28
      相关资源
      最近更新 更多