We begin by defining a schema for the loader options so we can validate them with schema-utils. The schema is an object that describes properties that you can set when you integrate the loader in your webpack config:
Next, we have the loader function itself:
This function accepts two arguments. 'loaderContext' is the context in which the loader runs. We'll use this to obtain some information about the loader, including the options. 'source' is the contents of the input file as a string (a yaml string in this instance). The function performs the following tasks:
- Call 'loaderContext.async()' to tell the loader that the process will run asynchronously. 'loaderContext.async()' returns a callback that we'll use to pass the results of the process back to the loader.
- Obtain the loader options by calling 'getOptions(loaderContext)', which is a function provided by loader-utils. We default the return value of 'getOptions' to an empty object literal in case the webpack config doesn't include the options hash.
- Validate the loader options against the schema we created earlier. This will throw an error if the options aren't specified correctly in the webpack config. Unpack the options, if desired.
- Parse the 'source' string. We're using js-yaml for this.
- At this point the data is parsed and you can perform additional validations and transformations on it.
- Json-serialize the data using 'JSON.stringify()'. Set the indentation according to your preferences (2 spaces in this case).
- Create the file contents for ECMA and CommonJS modules by appending the serialized json string to the export statement.
- Execute the callback with the appropriate file content string based on the 'commonjs' option.
Integration with webpack is similar to any other loader. Add a new rule to the 'module.rules' array in your webpack config. The rule should 'test' files for the '.yaml' file extension, 'exclude' any files in the 'node_modules' directory and 'use' your custom yaml loader:
You can use this loader for simple yaml files, or as a starting point for a more complex loader of your own.