I'd like to read and parse a static yaml resource file (let's starts from there) within my React Native source code, I tried require('path/to/file.yaml')
to no avail.
I also tried with npm's libraries such as read-yaml
or yaml-loader
all of which cannot get the yaml content properly.
It is a breeze with json file, I can just `require('path/to/file.json') and immediately get everything in nice object format.
Is there a way to read yaml in react native? It is just another text file right with a different format right, so I don't think it will be that hard to read and parse the yaml file., but I am new to JavaScript and React-Native here coming from C/C++ background
Since there appears to be no built-in support for yaml, I believe you would need to use something like react-native-fs , or in Expo FileSystem.readAsStringAsync (treating the file as an asset). You should then be able to use a library such as yaml-js to parse the string as read.
You can't use require directly to load yaml. If you're using Expo:
const [assets, assetsLoadError] = useAssets([
require(uri)
]);
const loadedAsset = await Asset.loadAsync(
require(uri)
);
let content;
try {
content = await FileSystem.readAsStringAsync(
loadedAsset.localUri
);
} catch (e) {
console.log({ e });
}
const parsedYAML = YAML.parse(content);
First install npm install --save babel-plugin-content-transformer
Then add to your babel config :
plugins: [
[
'content-transformer',
{
transformers: [
{
file: /\.ya?ml$/,
format: 'yaml',
},
],
},
],
],
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.