Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An easy and bundler agnostic way to use a sprite-sheet for your svgs. With server side rendering in mind

License

NotificationsYou must be signed in to change notification settings

kaoDev/react-lazy-svg

Repository files navigation

sloth emoji

react-lazy-svg

The easy way to use SVG sprite-sheets

GitHub licensenpmnpmGitHub issuesminified bundle size

react-lazy-svg is a simple way to use SVGs with the performance benefits of asprite-sheet and svg css styling possibilities. Without bloating the bundle. Itautomatically creates a sprite-sheet for all used SVGs on the client but alsoprovides a function to create a server side rendered sprite-sheet for icons usedin the first paint. So you can inject the critical svg

Usage

npm install --save react-lazy-svg

Examples on how to use react-lazy-svg with remix and next.js can be found in the./example-nextjs/ and./example-remix/directory.

Wrap the App with the contextProvider and provide a function to resolve SVGstrings by URL. If you are using server side rendering you should also callinitOnClient() to hydrate the sprite sheet context.

import{SpriteContextProvider,initOnClient.Icon}from'react-lazy-svg';importicon1from'./icon1.svg';constloadSVG=async(url:string)=>{returnawait(awaitfetch(url)).text();};initOnClient();constRoot=()=>(<SpriteContextProviderloadSVG={loadSVG}><Iconurl={icon1}className="icon"></Icon><Iconurl={icon1}className="icon red"></Icon></SpriteContextProvider>);

On the server the SVG resolver function could look like this, and load the svgcontents from the file system.

constsvgIconFiles=newMap<string,string>();constreadFile=promisify(fs.readFile);constcdnBase='http://localhost:3001/static/media/';exportconstreadSvg=async(url:string)=>{if(svgIconFiles.has(url)){returnsvgIconFiles.get(url);}if(url.startsWith(cdnBase)){url=path.join(process.cwd(),url.replace(cdnBase,'./build/public/static/media/'),);constsvgString=awaitreadFile(url,{encoding:'utf8'});svgIconFiles.set(url,svgString);returnsvgString;}returnundefined;};

About

An easy and bundler agnostic way to use a sprite-sheet for your svgs. With server side rendering in mind

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp