Modyfi / vite-plugin-yaml

Transform a YAML file to a JS object
75 stars 15 forks source link

loading yaml with numeric keys #30

Open sodiumjoe opened 2 months ago

sodiumjoe commented 2 months ago

Revisiting this issue, I don't think the raw config is quite the correct solution.

The original issue is that this plugin unquotes numeric keys:

❯ node
Welcome to Node.js v18.14.0.
Type ".help" for more information.
> yaml = require('@modyfi/vite-plugin-yaml')
{ default: [Function: src_default] }
> await yaml.default().transform(`
... '07': foo
... `, "foo.yaml")
{
  code: 'const data = { 07:"foo" };\nexport default data;',
  map: { mappings: '' }
}
>

Which, as the above issue notes, results in an error because of the leading 0.

The problem with raw mode is it fails on objects:

> await yaml.default({raw: true}).transform(`
... foo: bar
... `, "foo.yaml")
{
  code: 'const data = [object Object];\nexport default data;',
  map: { mappings: '' }
}

The above issue correctly identified tosource as the culprit here. Since js-yaml.load returns plain JSON, I'm not sure why tosource is necessary at all, as opposed to just JSON.stringify.

Happy to submit a PR if that sounds reasonable.

sodiumjoe commented 2 months ago

Another option is to use JSON.stringify when raw is true.

Pistonight commented 2 months ago

Another option is to use JSON.stringify when raw is true.

I was looking for a similar config to https://vitejs.dev/config/shared-options.html#json-stringify for performance A stringify option would be nice, instead of raw, which I feel have very limited use cases since they only work on scalar?