'Unable to find svgs assets with Parcel in React and TS

I've added parcel to a create-react-app project that uses the typescript template. I'm trying to add svgs to my outputted js file following the recommendations from their docs. I'm not sure if there's something that has to be done differently in TS, but I set up my project as they suggested as their JSX snippets and it didn't work:

.parcelrc

{
  "extends": "@parcel/config-default",
  "transformers": {
    "jsx:*.svg": ["...", "@parcel/transformer-svg-react"]
  }
}

Note: I've added the transformer plugin to my dev deps.

Component.tsx

import BriefcaseSvg from "jsx:../../assets/briefcase.svg";

// ...later in my return statement:
<img src={BriefcaseSvg} alt="work icon" />

// I've also tried
<BriefcaseSvg/>

Every time I get the following error:

Cannot resolve dependency 'jsx:../../assets/briefcase.svg'

I've also tried converting both jsx declarations to tsx.

I've added parcel on top of the standard webpack build tool you get with CRA. Wepback has no problem and displays the icon just find. Parcel also was able to run a build when I didn't include this svg plugin but outputted the svg separately in its own file.

I'd like everything to end up in one js file. How can I achieve this with parcel, react, and TS?



Solution 1:[1]

The default parcel config defines an svg transformer and optimizer, which are not properly resolving imports. You can follow the issue on GitHub at https://github.com/parcel-bundler/parcel/issues/7587.

As a workaround (for any type of import), you do not need to import a transformer.

Replace "jsx:" with "url:" in your import like this:

import BriefcaseSvg from "url:../../assets/briefcase.svg";

And use the src attribute, not a component.

<img src={BriefcaseSvg} alt="work icon" />

You can read more about the syntax at https://github.com/parcel-bundler/parcel/pull/4055. It only works in JS and was meant to support importing files that are not explicitly supported.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1