I'm using the create-react-app
library and I've created an SVG component that works well in development. My problem is that when building the application to publish, the build process doesn't recognize my component's dynamic paths and therefore doesn't put the main sprite file into my /media
folder.
Example SVG Component:
render() {
return (
<svg className={`icon ${this.props.id}`} fill={this.props.fill}>
<use xlinkHref={`/src/assets/images/svg-sprite/svg-sprite-${this.props.category}-symbol.svg#ic_${this.props.id}_24px`}></use>
</svg>
);
}
As you can see I'm referencing specific symbols in specific sprite files.
If you ejected before 0.5.0, import
ing assets is the only way to get them added into the build output. There are good reasons for this: for example, their filenames automatically include a hash because build system is aware of them, so you don't need to worry about busting browser caches when the file changes. You also don't need to worry about typos because a missing file will give you a compilation error.
Since 0.5.0, we also support a public
folder as an escape hatch. You can put any files in the public
folder, and they will be merged with the build output. The only gotcha is that to reference them, you need to add process.env.PUBLIC_URL
to your links. This ensures that if you build a project for a non-root URL (like GitHub Pages), it still works correctly.
<use linkHref={process.env.PUBLIC_URL + `/assets/images/svg-sprite/svg-sprite-${this.props.category}-symbol.svg#ic_${this.props.id}_24px`}></use>
would work as long as your public
folder contains assets/images/svg-sprite/svg-sprite-*
files.
Please note again that this feature is only available since [email protected]
so if you ejected earlier, you might need to backport it to your project.
Reference: