Importing YAML data at build-time in Webpack, and making it available as parsed data at runtime

Viewed 5047

I'm attempting to import the contents of a YAML file at build-time, and make the parsed content available to my application somehow.

This is in a Webpack project that I've been tasked with building a new feature for. The project is using Vue. I have pretty much 0 experience with Webpack. I've installed the js-yaml-loader package, and have configured Webpack with it as such:

module: {
  rules: [
    ...,
    {
      test: /\.ya?ml$/,
      include: path.resolve(process.cwd(), 'src/data'),
      loader: 'js-yaml-loader'
    },
    ...
  ]
}

As far as I understand it, this will - at build time - traverse the src/data folder for YAML files, and load them, using the js-yaml-loader loader, which will then somehow include the parsed content of those files somewhere. But when I search the generated output, the keys/values contained in the YAML are nowhere to be found.

Am I going about this correctly? Or is there something I've misunderstood?

4 Answers

You need to import your .yaml file in some source file in your project.

You can imagine webpack loaders defined in module.rules as some scripts or programs that will run when you are trying to import a file fulfilling some pattern (test property) (there can be also another condition that should be fulfilled, e.g. your include condition). The loader will take your file as an input and provide some output.

So you need to import your file, e.g. in some of your .js file:

import myYamlFile from './file.yml';

Then according to js-yaml-loader documentation you have your file as a javascript object in variable myYamlFile, see the documentation of js-yaml parser:

https://github.com/nodeca/js-yaml

This is how I solved it with Vue + TypeScript:

  1. Create a yaml file e.g. test.yaml.

  2. Create typings for it with e.g. test.yaml.d.ts, register it to be used with js-yaml-loader e.g.:

       declare module 'js-yaml-loader!*' { 
              export interface TestYaml {
                     testProperty: string;
              }
    
              const content: TestYaml ;
              export default content;
       }
    
  3. Import it using import { MyYamlFile} from 'js-yaml-loader!./../test.yaml';

Example:

In the end, I didn't even have to modify the Webpack config. I just did this:

import TextData from 'js-yaml-loader!../data/texts.yaml';
import Texts from './vue/plugins/texts';
Vue.use(Texts, {
    texts: TextData,
});

Which imports the text data as a JS oject and injects in into the options for my Texts Vue plugin.

I had a similar challenge (loading yaml files in vuejs at build time), and I used vue-cli-plugin-yaml.

No webpack configuration needed, and once installed you can import the files easily.

import myData from './myData.yaml';
console.log(myData);
Related