Skip to content

hubper/snowpack-svgr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

snowpack-svgr

Snowpack plugin to transform your React components using svgr

Types NPM Version

snowpack-svgr will make sure you can use your SVG files as ReactComponents just like you were used to with create-react-app but with all the benefits of Snowpack.

  • Supports both url and as ReactComponent imports
  • Allows custom SVGR and Babel configuration
  • Works in a monorepo setup
  • Covered by unit tests

Install

yarn add -D snowpack-svgr
// snowpack.config.json

{
    plugins: [["snowpack-svgr", { /** SnowpackSVGROptions */ }]
}

Options

type SnowpackSVGROptions = {
    /**
     * If true the default export will be the url of the asset.
     * The ReactComponent will be exported via the ReactComponent named export
     */
    exportUrlAsDefault?: boolean; // false
    /**
     * Options used by @svgr/core
     * @see See: https://react-svgr.com/docs/options/
     */
    svgrOptions?: Record<string, unknown>; // {}
    /**
     * Options used by babel.loadPartialConfig()
     */
    babelOptions?: babel.TransformOptions; // {}
}

Usage

By default the plugin will export a React component when importing a .svg file

import Image from "./image.svg";

<Image {...props} />

When the option exportUrlAsDefault is true. The plugin will make sure the default export is the url to the SVG asset. The ReactComponent will be exported by the ReactComponent named export.

import imageUrl, { ReactComponent as Image } from "./image.svg";

<>
 The <Image {...props} /> can be found at {imageUrl}
</>

Types

Modify your types/static.d.ts file accordingly.

// replace
declare module '*.svg' {
  const ref: string
  export default ref
}

// exportUrlAsDefault: true
declare module "*.svg" {
  export const ReactComponent: React.ForwardRefRenderFunction<
      SVGSVGElement,
      React.SVGAttributes<SVGSVGElement>
  >;
  const src: string;
  export default src;
}

// exportUrlAsDefault: false
declare module "*.svg" {
    const ReactComponent: React.ForwardRefRenderFunction<
        SVGSVGElement,
        React.SVGAttributes<SVGSVGElement>
    >;
    export default ReactComponent;
}

LICENCE

MIT