3

I'm trying to import a yaml file in React Native. I can see in the Metro defaults.js file that yaml is listed as an asset extension already.

The imported value is always the number 1 though and not the actual contents of the yaml file.

import enYaml from '../i18n/locale/en.yaml';

Debugger screenshot

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182

1 Answers1

2

That is because you're loading it as a resource. So it's the resource ID. What you'd need is an answer for What is the equivalent of a webpack loader when using the metro bundler in React Native?

To do this in Expo which uses babel.config.js which Metro uses you need to add the babel-plugin-content-transformer as a dev dependency and configure it as follows

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'content-transformer',
        {
          transformers: [
            {
              file: /\.ya?ml$/,
              format: 'yaml',
            },
          ],
        },
      ],
   ...
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • This isn't working for me, I've set it up exactly like this but my yaml is still getting loaded as a number. Any ideas? – Nathan Oct 01 '22 at 06:19
  • To elaborate a bit, I'm using React Native + Expo and trying to import a yaml file. I'm using typescript, and I declared `declare module '*.yaml' { const data: string export default data }` ( I know this solution loads yamls as objects, not strings, but I tried loading as a string as well and still got a number). – Nathan Oct 01 '22 at 06:26
  • if you want to load the yaml file as a string then you use format: "string" rather than YAML – Archimedes Trajano Oct 01 '22 at 20:33
  • I tried that, neither "string" nor "yaml" seems to work, it always returns a number. It seems like the transformer isn't working at all. I made another question about this if you don't mind checking it out: https://stackoverflow.com/questions/73920985/babel-plugin-content-transformer-is-not-working-on-a-react-native-expo-project – Nathan Oct 01 '22 at 20:46
  • (it was a cache issue, all good now) – Nathan Oct 05 '22 at 07:28