简体   繁体   中英

Import a YAML file in React with craco and yaml-loader

I am having a quite difficult time trying to import a YAML file as a JS object in my React code.

I made this simple and reproductible CodeSandbox example built with create-react-app to show my problem.

All I am doing is:

  • configuring Webpack in a craco.config.js file (as recommended in the craco docs ),
  • adding some Webpack configuration code for the YAML loader (as recommended in the yaml-loader docs ).
  • importing the YAML file in the index.js file so I can use it as a JS object.
// craco.config.js

module.exports = {
  webpack: {
    configure: {
      module: {
        rules: [
          {
            test: /\.yaml$/,
            use: "yaml-loader"
          }
        ],
      },
    },
  },
};
// index.js
...
import testYamlFile from "./testYamlFile.yaml"

ReactDOM.render(
  <>
    <p>Parsed test YAML file object: {testYamlFile}</p>
    <p>Type of parsed object: {typeof testYamlFile}</p>
  </>,
  document.getElementById("root")
);

// Output in CodeSandbox browser:

Parsed test YAML file object: data:application/octet-stream;base64,aGVsbG9Xb3JsZEZvck1vZGVsOiBIZWxsbywgZGVhciBtb2RlbCAhCg==
Type of parsed object: string

In the CodeSandbow example, I am getting a base64 string, so you would tell me that I simply need to decode it and get the content. But there are two things:

  • first, this is not what is intended: I should get a JS object according to the yaml-loader docs
  • and second, what I get on my PC -- and I can only reproduce it on my machine, despite my best efforts to reproduce the exact same project in CodeSandox -- is even weirder. Actually, I only get the bundled file path, and that's all:

它在我的机器上做了什么

// Output in my own local browser:

Parsed test YAML file object: /static/media/testYamlFile.5a3cab37.yaml
Type of parsed object: string

I suppose that because Webpack added its unique ID to the file name, it is recognizing and bundling the yaml file. But I don't understand why I can't access its content in my code.

Also tried with js-yaml-loader instead of yaml-loader : same issue. What am I doing wrong? Thanks for your help.

Same problem here. I originally thought it was the craco version issue (As I add the package via yarn add craco instead of yarn add -D @craco/craco ) but no, same result. It took me days to find a solution for this, tried different configurations in craco.config.js, but still no luck. I eventually use workarounds for this until the root cause found.

  1. Use fetch method, retrieve the yaml files as static content via http requests
  2. Use "i18next-http-backend" if the yaml is for react-i18next

Update, I finally made it work by doing some magic in craco.config.js . The craco helpers did not help much, my goal is to make the assets loader (without loader name, you have to use your own matcher to find the loader) ignore the yaml extensions, then add new rule to resolve the yaml content. Final code is like below:

module.exports = {
    
plugins: [
    {
        plugin: {
            overrideWebpackConfig: ({ context, webpackConfig }) => {
                console.log(webpackConfig.module.rules.find(rule => rule.hasOwnProperty('oneOf')));
                const { isFound, match: fileLoaderMatch } = getLoader(
                    webpackConfig,
                    rule => rule.type === 'asset/resource'
                );

                if (!isFound) {
                    throw {
                        message: `Can't find file-loader in the ${context.env} webpack config!`
                    };
                }

                fileLoaderMatch.loader.exclude.push(/\.ya?ml$/);

                const yamlLoader = {
                    use: 'yaml-loader',
                    test: /\.(ya?ml)$/,
                };
                webpackConfig.module.rules.push(yamlLoader);
                return webpackConfig;
            },
        }
    },
],
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM