I tried to install react-native-svg-transformer into my Expo project, so I can
- load PNG and other image files from
assets, - transform SVG files,
- use
@/src/...as alias.
When I start the project, I see a lot of wild errors but essentially it seems to come down to Check your code at _layout.tsx:54.
When I remove that line, the project compiles and runs fine.
I created metro.config.ts and this is what I currently have:
const { getDefaultConfig } = require("expo/metro-config");
module.exports = (() => {
const config = getDefaultConfig(__dirname);
const { transformer, resolver } = config;
config.transformer = {
...transformer,
babelTransformerPath: require.resolve("react-native-svg-transformer")
};
config.resolver = {
...resolver,
assetExts: [...resolver.assetExts, "png", "jpg", "jpeg", "gif"],
sourceExts: [...resolver.sourceExts, "svg"],
moduleNameMapper: {
"^@(.*)": "<rootDir>$1"
}
};
return config;
})();
There are a lot of slightly distinct versions floating around the web, but I settled on allowing to import certain assets like PNG and to run SVGs through the transformer.
In babel.config.ts I added the plugins:
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
"module-resolver",
{
root: ["."],
extensions: [".ios.js", ".android.js", ".js", ".ts", ".tsx", ".json"],
alias: {
"@": "."
}
}
]
]
};
};
Somewhere I was told to add declarations.d.ts which I think is irrelevant here:
declare module "*.svg" {
import React from "react";
import { SvgProps } from "react-native-svg";
const content: React.FC<SvgProps>;
export default content;
}
I managed to locate the SVG file for the import but then the error happens where I transform the SVG (the ominous line 54 which I see in the logs):
import Logo from "@/src/assets/images/icon.svg";
...
<Logo height={40} style={styles.headerLeft} />
The style works, tried it with another element, but included it here for a "full disclosure". ;-)
I managed to get row and column where the issue happens, but it points me to the empty space in front of the command. This looks very much like somehow the code isn't properly transformed (source and compiled versions aren't the same). I cleared all caches to ensure this is not the case, but the issue persists.
It doesn't become clear to me where the difference is between the babel alias and the metro moduleNameMapper and if we need both. I tried to remove either of these, but the problem didn't go away.
I believe the remaining Megabytes of logs are not needed, but in case you need more logs, let me know.
- Could anybody please check my configuration files if you see any errors.
- Do I really need both files and can/or the configs be skimmed further down? And maybe you can explain to me how these files interact in relation to the different filetypes, e.g. what's processed first and what later.