简体   繁体   中英

Creating an SVG Sprite component with ejected create-react-app

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 react-scripts@0.5.0 so if you ejected earlier, you might need to backport it to your project.

Reference:

In case anyone runs into this issue... I looked into the webpack.config.prod.js and found a comment that says any files you import get built into the /media folder. Fixed my problem by importing all of my SVG sprite files which isn't ideal but got the job done.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM