在 React Native 中导入 yaml 文件导致数字 1 而不是实际内容

Import yaml file in React Native results in number 1 instead of actual content

我正在尝试在 React Native 中导入一个 yaml 文件。我可以在 Metro defaults.js 文件中看到 yaml 已经被列为资产扩展。

导入的值始终是数字 1,而不是 yaml 文件的实际内容。

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

那是因为您将其作为资源加载。所以它是资源ID。您需要的是 What is the equivalent of a webpack loader when using the metro bundler in React Native?

的答案

要在使用 Metro 使用的 babel.config.js 的 Expo 中执行此操作,您需要添加 babel-plugin-content-transformer 作为开发依赖项并按如下方式配置它

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'content-transformer',
        {
          transformers: [
            {
              file: /\.ya?ml$/,
              format: 'yaml',
            },
          ],
        },
      ],
   ...