yaml.macro
raw JSON → 0.2.0 verified Sat Apr 25 auth: no javascript
A Babel macro for loading YAML files at build time, transforming YAML into JavaScript objects via babel-plugin-macros. Current stable version is 0.2.0, released infrequently. It uses the `yaml` package under the hood and supports all its parser options. Key differentiators: integrates seamlessly with Babel macros, evaluated at build time (not runtime), supports any YAML 1.2 types. Unlike runtime YAML loaders, this macro inlines data at compile time, reducing bundle size and runtime overhead. Requires Node.js >=10 and babel-plugin-macros.
Common errors
error yaml.macro is not a function ↓
cause Attempting to use require() or named import instead of default import.
fix
Use import yaml from 'yaml.macro'
error Cannot find module 'babel-plugin-macros' ↓
cause Missing babel-plugin-macros package or not installed as dev dependency.
fix
npm install --save-dev babel-plugin-macros
error The macro threw an error: 'path' is not defined ↓
cause Passing a variable or expression as the path argument instead of a string literal.
fix
yaml('./your-file.yaml') — path must be a string literal
Warnings
gotcha The path argument must be a string literal starting with '.' for relative paths or an absolute path. Dynamic expressions or variables are not evaluated at build time and will cause errors. ↓
fix Use a constant string: yaml('./myfile.yaml') not yaml(filePathVariable)
gotcha Multiple calls to the same YAML file are not cached. Each call will re-parse the file, increasing build time. ↓
fix Assign the result to a variable and reuse it: const data = yaml('./file.yaml'); then use data multiple times.
breaking Version 0.2.0 requires Node.js >=10. Older versions (0.1.x) may work on Node 8 but are unsupported. ↓
fix Upgrade Node.js to version 10 or higher.
deprecated The macro uses the 'yaml' package version 2 internally. If you rely on specific parsing behavior from older versions, check compatibility. ↓
fix Refer to yaml package changelog for breaking changes between versions.
Install
npm install yaml.macro yarn add yaml.macro pnpm add yaml.macro Imports
- default wrong
const yaml = require('yaml.macro')correctimport yaml from 'yaml.macro' - yaml wrong
import { yaml } from 'yaml.macro'correctimport yaml from 'yaml.macro'; yaml('./file.yaml') - yaml with options wrong
import yaml from 'yaml.macro'; yaml('./file.yaml', { schema: 'core' }, extraArg)correctimport yaml from 'yaml.macro'; yaml('./file.yaml', { schema: 'core' })
Quickstart
// Install: npm install --save-dev yaml.macro babel-plugin-macros
// .babelrc or babel.config.js:
{
"plugins": ["macros"]
}
// myData.yaml:
// - item1
// - item2: value
// myFile.js:
import yaml from 'yaml.macro';
const myData = yaml('./myData.yaml');
console.log(myData); // ['item1', { item2: 'value' }]
export default myData;