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:
craco.config.js
file (as recommended in the craco
docs ),yaml-loader
docs ).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:
// 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.
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.