### Install @svgr/hast-util-to-babel-ast Source: https://github.com/gregberge/svgr/blob/main/packages/hast-util-to-babel-ast/README.md Instructions on how to install the @svgr/hast-util-to-babel-ast package as a development dependency. ```APIDOC ## Install ```bash npm install --save-dev @svgr/hast-util-to-babel-ast ``` ``` -------------------------------- ### Install @svgr/webpack Source: https://github.com/gregberge/svgr/blob/main/packages/webpack/README.md Install the package as a development dependency using npm. ```bash npm install @svgr/webpack --save-dev ``` -------------------------------- ### Install @svgr/plugin-jsx Source: https://github.com/gregberge/svgr/blob/main/packages/plugin-jsx/README.md Command to install the plugin as a development dependency in your project. ```bash npm install --save-dev @svgr/plugin-jsx ``` -------------------------------- ### Install @svgr/hast-util-to-babel-ast via npm Source: https://github.com/gregberge/svgr/blob/main/packages/hast-util-to-babel-ast/README.md Command to install the package as a development dependency in your project. ```bash npm install --save-dev @svgr/hast-util-to-babel-ast ``` -------------------------------- ### Install @svgr/plugin-prettier Source: https://github.com/gregberge/svgr/blob/main/packages/plugin-prettier/README.md Installs the @svgr/plugin-prettier package as a development dependency using npm. ```bash npm install --save-dev @svgr/plugin-prettier ``` -------------------------------- ### Install @svgr/babel-plugin-transform-react-native-svg Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-transform-react-native-svg/README.md Command to install the plugin as a development dependency in your project. ```bash npm install --save-dev @svgr/babel-plugin-transform-react-native-svg ``` -------------------------------- ### Install Dependencies and Build (pnpm) Source: https://github.com/gregberge/svgr/blob/main/CONTRIBUTING.md Commands to install project dependencies and build the project using pnpm, a package manager recommended for SVGR. ```sh pnpm install pnpm run build ``` -------------------------------- ### Install SVGR Core Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Install the SVGR core package as a development dependency. ```APIDOC ## Install SVGR Core Use SVGR in Node.js to complex transformations or tools. ### Installation ```bash npm install --save-dev @svgr/core # or use yarn yarn add --dev @svgr/core ``` ``` -------------------------------- ### Jest Mocking for SVG Imports (JavaScript) Source: https://context7.com/gregberge/svgr/llms.txt Provides configurations for Jest to mock SVG file imports in React projects. Includes examples for a mock file (`__mocks__/svg.js`), Jest configuration (`jest.config.js`), an alternative `package.json` setup, and a sample test case using `@testing-library/react`. Requires Jest and React. ```javascript // __mocks__/svg.js - SVG mock file export default 'SvgrURL' export const ReactComponent = 'div' ``` ```javascript // jest.config.js module.exports = { moduleNameMapper: { '\.svg$': '/__mocks__/svg.js', }, } ``` ```json // package.json alternative { "jest": { "moduleNameMapper": { "\.svg$": "/__mocks__/svg.js" } } } ``` ```javascript // Example test import { render } from '@testing-library/react' import Logo from './logo.svg' test('renders logo', () => { const { container } = render() expect(container.querySelector('div')).toBeInTheDocument() }) ``` -------------------------------- ### Install @svgr/webpack Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Install the SVGR webpack loader using npm or yarn. ```APIDOC ## Install @svgr/webpack ### Description Install the SVGR webpack loader using npm or yarn. ### Command ```bash npm install --save-dev @svgr/webpack # or use yarn yarn add --dev @svgr/webpack ``` ``` -------------------------------- ### SVGR Configuration Example (JSON) Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/configuration-files.mdx Example of SVGR configuration in JSON format. This configuration can be placed in a .svgrrc.json file or within the 'svgr' key of a package.json file. It specifies options like 'icon' and 'expandProps'. ```json { "icon": true, "expandProps": false } ``` -------------------------------- ### Install @svgr/babel-plugin-remove-jsx-empty-expression Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-remove-jsx-empty-expression/README.md Command to install the plugin as a development dependency using npm. ```bash npm install --save-dev @svgr/babel-plugin-remove-jsx-empty-expression ``` -------------------------------- ### Install @svgr/babel-plugin-transform-svg-component Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-transform-svg-component/README.md Installs the @svgr/babel-plugin-transform-svg-component package as a development dependency using npm. ```bash npm install --save-dev @svgr/babel-plugin-transform-svg-component ``` -------------------------------- ### Using SVGO and Prettier Plugins Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Instructions on how to install and use SVGO and Prettier plugins with SVGR for enhanced SVG optimization and formatting. ```APIDOC ## Use SVGO and Prettier By default `@svgr/core` doesn't include `svgo` and `prettier` plugins. If you need these, you have to install them and specify them in options. ### Installation ```bash npm install @svgr/plugin-jsx @svgr/plugin-prettier ``` ### Usage Specify the plugins in the `options` object passed to the `transform` function. ```js import { transform } from '@svgr/core' const svgCode = ` ` const jsCode = await transform( svgCode, { plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'], icon: true, }, { componentName: 'MyComponent' }, ) console.log(jsCode) ``` ``` -------------------------------- ### Install @svgr/babel-plugin-add-jsx-attribute Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-add-jsx-attribute/README.md Command to install the plugin as a development dependency in your project using npm. ```bash npm install --save-dev @svgr/babel-plugin-add-jsx-attribute ``` -------------------------------- ### Install @svgr/rollup Source: https://github.com/gregberge/svgr/blob/main/packages/rollup/README.md Install the @svgr/rollup package as a development dependency using npm. ```bash npm install @svgr/rollup --save-dev ``` -------------------------------- ### Run Development Server (pnpm) Source: https://github.com/gregberge/svgr/blob/main/CONTRIBUTING.md Starts the development server in watch mode, which continuously transforms changed files, useful for testing during development. ```sh pnpm run dev ``` -------------------------------- ### Configure SVGR with Plugins Source: https://github.com/gregberge/svgr/blob/main/packages/core/README.md Shows how to apply specific plugins like svgo, jsx, and prettier during the transformation process. Plugins must be installed separately and passed within the configuration object. ```javascript svgr(svgCode, { plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'], }).then((jsCode) => { console.log(jsCode) }) ``` -------------------------------- ### Install @svgr/babel-plugin-svg-dynamic-title Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-svg-dynamic-title/README.md Command to install the plugin as a development dependency in your project using npm. ```bash npm install --save-dev @svgr/babel-plugin-svg-dynamic-title ``` -------------------------------- ### Install SVGR Webpack loader Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/next.mdx Commands to install the @svgr/webpack dependency using npm or yarn. ```bash npm install --save-dev @svgr/webpack yarn add --dev @svgr/webpack ``` -------------------------------- ### Install @svgr/babel-plugin-svg-em-dimensions Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-svg-em-dimensions/README.md Installs the @svgr/babel-plugin-svg-em-dimensions package as a development dependency using npm. ```bash npm install --save-dev @svgr/babel-plugin-svg-em-dimensions ``` -------------------------------- ### SVGR Configuration Example (YAML) Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/configuration-files.mdx Example of SVGR configuration in YAML format, commonly used in a .svgrrc.yaml file. This provides a human-readable way to define SVGR options. ```yaml # .svgrrc icon: true expandProps: false ``` -------------------------------- ### Usage Example Source: https://github.com/gregberge/svgr/blob/main/packages/hast-util-to-babel-ast/README.md Demonstrates how to use the hastToBabelAst function by parsing an SVG string into HAST and then converting it to Babel AST. ```APIDOC ## Usage ```javascript import { parse } from 'svg-parser' import hastToBabelAst from '@svgr/hast-util-to-babel-ast' const hastTree = parse('') const babelTree = hastToBabelAst(hastTree) ``` ``` -------------------------------- ### Install SVGR CLI Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/cli.mdx Commands to install the @svgr/cli package as a development dependency using npm or yarn. ```bash npm install --save-dev @svgr/cli yarn add --dev @svgr/cli ``` -------------------------------- ### Install @svgr/babel-plugin-remove-jsx-attribute Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-remove-jsx-attribute/README.md The installation command for adding the plugin to your project as a development dependency using npm. ```bash npm install --save-dev @svgr/babel-plugin-remove-jsx-attribute ``` -------------------------------- ### Install @svgr/core dependency Source: https://github.com/gregberge/svgr/blob/main/packages/core/README.md Command to install the @svgr/core package via npm for use in Node.js projects. ```bash npm install @svgr/core ``` -------------------------------- ### Transform SVG with Plugins (Async) Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Shows how to use SVGR with additional plugins like SVGO and Prettier for enhanced SVG optimization and formatting. Requires installing the respective plugins. ```bash npm install @svgr/plugin-jsx @svgr/plugin-prettier ``` ```javascript import { transform } from '@svgr/core' const svgCode = ` ` const jsCode = await transform( svgCode, { plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'], icon: true, }, { componentName: 'MyComponent' }, ) ``` -------------------------------- ### Install SVGR JSX Plugin Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/custom-transformations.mdx Commands to install the @svgr/plugin-jsx package using npm or yarn package managers. ```bash npm install @svgr/plugin-jsx yarn add @svgr/plugin-jsx ``` -------------------------------- ### Install SVGR Core Package Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Installs the SVGR core package as a development dependency using npm or yarn. ```bash npm install --save-dev @svgr/core # or use yarn yarn add --dev @svgr/core ``` -------------------------------- ### SVGR Configuration Example (JS) Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/configuration-files.mdx Example of SVGR configuration using a JavaScript file, typically named svgr.config.js or .svgrrc.js. This method allows for more complex configurations using module.exports. ```javascript // .svgrrc.js module.exports = { icon: true, expandProps: false, } ``` -------------------------------- ### Configure Babel for Attribute Injection Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-add-jsx-attribute/README.md Example configuration for .babelrc to specify which elements receive attributes and the details of those attributes, including name, value, and positioning. ```json { "plugins": [ [ "@svgr/babel-plugin-add-jsx-attribute", { "elements": ["svg"], "attributes": [ { "name": "width", "value": "200", "spread": false, "literal": false, "position": "end" } ] } ] ] } ``` -------------------------------- ### SVGR Rollup Configuration with Options Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/rollup.mdx Illustrates how to pass options to the @svgr/rollup plugin directly within the rollup.config.js file. This example shows setting the 'icon' option to true. ```javascript import svgr from '@svgr/rollup' export default { plugins: [svgr({ icon: true })], input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs', }, } ``` -------------------------------- ### Install @svgr/rollup Plugin Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/rollup.mdx Installs the SVGR Rollup plugin using npm or yarn. This is the first step to enable SVGR functionality within your Rollup build process. ```bash npm install --save-dev @svgr/rollup # or use yarn yarn add --dev @svgr/rollup ``` -------------------------------- ### Install SVGR Dependencies for Remix Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/remix.mdx Installs the necessary SVGR packages and development tools like npm-watch and npm-run-all for managing SVG conversion tasks in a Remix project. ```bash npm install --save-dev @svgr/cli @svgr/plugin-svgo @svgr/plugin-jsx @svgr/plugin-prettier npm-watch npm-run-all ``` -------------------------------- ### Rollup Plugin Setup for SVGR Source: https://context7.com/gregberge/svgr/llms.txt Enables SVG component imports in Rollup build systems using the `@svgr/rollup` plugin. Supports basic setup, advanced options, and URL export when combined with `@rollup/plugin-url`. ```javascript // rollup.config.js - Basic setup import svgr from '@svgr/rollup' export default { plugins: [svgr()], input: 'src/main.js', output: { file: 'bundle.js', format: 'esm', } } // rollup.config.js - With options import svgr from '@svgr/rollup' export default { plugins: [ svgr({ icon: true, memo: true, ref: true, replaceAttrValues: { '#000': 'currentColor' }, }) ], input: 'src/main.js', output: { file: 'bundle.js', format: 'esm' }, } // rollup.config.js - With URL support import url from '@rollup/plugin-url' import svgr from '@svgr/rollup' export default { plugins: [url(), svgr({ icon: true })], input: 'src/main.js', output: { file: 'bundle.js', format: 'esm' }, } // Usage with named export import starUrl, { ReactComponent as Star } from './star.svg' const App = () => (
star
) ``` -------------------------------- ### Import SVG as React Component Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Example of importing an SVG file as a React component and rendering it within a functional component. ```javascript import Star from './star.svg' const Example = () => (
) ``` -------------------------------- ### Configure Babel Plugin for SVG Dimensions Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-svg-em-dimensions/README.md Configures the Babel build process to use the @svgr/babel-plugin-svg-em-dimensions plugin. This example shows how to set default width and height attributes for SVGs using a .babelrc file. ```json { "plugins": [ ["@svgr/babel-plugin-svg-em-dimensions", { "width": 24, "height": 24 }] ] } ``` -------------------------------- ### Import SVG as React Component or URL Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/next.mdx Examples of importing an SVG file directly as a React component or as a URL for use with the Next.js Image component. ```javascript import Star from './star.svg' const Example = () => (
) ``` ```javascript import Image from 'next/image' import starUrl from './star.svg?url' const Example = () => (
) ``` -------------------------------- ### Webpack Loader Setup for SVGR Source: https://context7.com/gregberge/svgr/llms.txt Integrates SVGR into webpack build pipelines to import SVGs as React components. Supports basic setup, advanced options like icons and TypeScript, and dual import modes (component and URL). ```javascript // webpack.config.js - Basic setup module.exports = { module: { rules: [ { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }, ], }, } // webpack.config.js - With options module.exports = { module: { rules: [ { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: [{ loader: '@svgr/webpack', options: { icon: true, typescript: true, memo: true, ref: true, svgo: true, svgoConfig: { plugins: [{ name: 'removeViewBox', active: false }], }, }, }], }, ], }, } // webpack.config.js - Support both URL and component imports module.exports = { module: { rules: [ { test: /\.svg$/i, type: 'asset', resourceQuery: /url/, // *.svg?url }, { test: /\.svg$/i, issuer: /\.[jt]sx?$/, resourceQuery: { not: [/url/] }, use: ['@svgr/webpack'], }, ], }, } // Usage in React component import Star from './star.svg' import starUrl from './star.svg?url' const App = () => (
star
) ``` -------------------------------- ### Define Custom Index Template Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/custom-templates.mdx Custom index templates process an array of file paths to generate a custom export structure for the output directory. This example creates an export map based on original file names. ```javascript const path = require('path') function defaultIndexTemplate(filePaths) { const entries = filePaths.map(({ path: filePath, originalPath }) => { const originalFileName = path.basename( originalPath, path.extname(originalPath), ) const basename = path.basename(filePath, path.extname(filePath)) const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename const importLine = `import ${exportName} from './${basename}';` const mapLine = `${/.*[.-].*/.test(originalFileName) ? `'${originalFileName}'` : originalFileName}: ${exportName}` return { importLine, mapLine } }) return `${entries.map(({ importLine }) => importLine).join('\n')} export const map = { ${entries.map(({ mapLine }) => mapLine).join(',\n')} } ` } module.exports = defaultIndexTemplate ``` -------------------------------- ### Define Custom Component Template Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/custom-templates.mdx A template function receives variables like componentName, props, and jsx, and uses the tpl helper to return a Babel AST. This example demonstrates adding PropTypes to the generated component. ```javascript const propTypesTemplate = ( { imports, interfaces, componentName, props, jsx, exports }, { tpl }, ) => { return tpl`${imports} import PropTypes from 'prop-types'; ${interfaces} function ${componentName}(${props}) { return ${jsx}; } ${componentName}.propTypes = { title: PropTypes.string, }; ${exports} ` } module.exports = propTypesTemplate ``` -------------------------------- ### Configure SVGR via configuration files Source: https://context7.com/gregberge/svgr/llms.txt Demonstrates how to define SVGR settings using JavaScript, JSON, or YAML formats. These files control component generation, optimization, and formatting options. ```javascript module.exports = { icon: true, typescript: true, memo: true, ref: true, exportType: 'default', jsxRuntime: 'automatic', svgProps: { role: 'img', 'aria-hidden': 'true' }, replaceAttrValues: { '#000000': 'currentColor' }, svgo: true, prettier: true, plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'] } ``` ```json { "icon": true, "typescript": true, "svgProps": { "role": "img" }, "replaceAttrValues": { "#000": "currentColor" } } ``` ```yaml icon: true typescript: true svgProps: role: img replaceAttrValues: '#000': currentColor ``` -------------------------------- ### SVGR v5.x vs v6.x Command Line Options Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/migrate.mdx Demonstrates the change in command-line syntax for SVGR, specifically how to use the `--` separator for arguments like `--icon` in v6.x compared to v5.x. ```sh svgr --icon assets/svg ``` ```sh svgr --icon -- assets/svg ``` -------------------------------- ### Create Custom Index Template Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/cli.mdx Defines a custom JavaScript template for generating index files and demonstrates how to apply it using the CLI. ```javascript const path = require('path') function defaultIndexTemplate(filePaths) { const exportEntries = filePaths.map(({ path: filePath, originalPath }) => { const basename = path.basename(filePath, path.extname(filePath)) const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename return `export { default as ${exportName} } from './${basename}'` }) return exportEntries.join('\n') } module.exports = defaultIndexTemplate ``` ```bash npx @svgr/cli --out-dir dist --index-template index-template.js -- icons ``` -------------------------------- ### Basic SVGR Rollup Configuration Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/rollup.mdx Demonstrates the basic configuration of the @svgr/rollup plugin in a rollup.config.js file. It shows how to import the plugin and include it in the Rollup plugins array. ```javascript import svgr from '@svgr/rollup' export default { plugins: [svgr()], input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs', }, } ``` -------------------------------- ### Configure SVGR Template via CLI and Config Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/custom-templates.mdx Shows how to apply a custom template using the SVGR CLI or by referencing it in the .svgrrc.js configuration file. ```bash npx @svgr/cli --template template.js -- my-icon.svg ``` ```javascript module.exports = { template: require('./my-template'), } ``` -------------------------------- ### Notes for Tool Creators Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Guidelines for developers building tools on top of SVGR, emphasizing best practices for interoperability and performance. ```APIDOC ## Note for Tools Creators If you want to create a tool based on SVGR, you must follow some rules to ensure compatibility and performance. ### Specify `state.caller` It is recommended to specify `state.caller` to enable interoperability between plugins. This allows SVGR plugins to adapt specifically to your tool. ```typescript interface State { filePath?: string componentName: string caller?: { name?: string previousExport?: string | null defaultPlugins?: ConfigPlugin[] } } ``` Additionally, you can specify `defaultPlugins` if your tool requires certain plugins by default, while still allowing users to customize them. ### Use Asynchronous API The asynchronous API uses Node.js's asynchronous capabilities, which generally leads to better performance. Use the asynchronous API whenever possible. ### Do Not Override SVGR Options SVGR provides a comprehensive set of options documented [here](https://react-svgr.com/docs/options/). It's best practice not to override these options within your tool, as it simplifies the user experience by allowing them to refer to the standard SVGR documentation. ``` -------------------------------- ### Webpack Configuration with Options Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Configure webpack.config.js to use @svgr/webpack with specific options. ```APIDOC ## Webpack Configuration with Options ### Description Configure webpack.config.js to use @svgr/webpack with specific options, such as `icon: true`. ### File `webpack.config.js` ### Code ```javascript module.exports = { module: { rules: [ { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: [{ loader: '@svgr/webpack', options: { icon: true } }], }, ], }, } ``` ### Note Refer to the [SVGR options reference](https://react-svgr.com/docs/options/) for a complete list of available options. ``` -------------------------------- ### Basic SVGR Component Usage Source: https://github.com/gregberge/svgr/blob/main/website/pages/index.mdx Demonstrates how to import and render an SVG file as a React component. This approach assumes the project is configured with the SVGR loader or plugin. ```javascript import React from 'react'; import SvgIcon from './icon.svg'; const App = () => (
); ``` -------------------------------- ### Run Test Suite (pnpm) Source: https://github.com/gregberge/svgr/blob/main/CONTRIBUTING.md Executes the project's test suite to ensure all tests pass before submitting changes. ```sh pnpm run test ``` -------------------------------- ### Configure SVGR with Options Source: https://github.com/gregberge/svgr/blob/main/packages/webpack/README.md Pass specific options to the loader, such as enabling native support or configuring Babel settings. ```javascript { test: /\.svg$/, use: [ { loader: '@svgr/webpack', options: { native: true, }, }, ], } ``` -------------------------------- ### Custom SVGR Babel Transformations (JavaScript) Source: https://context7.com/gregberge/svgr/llms.txt Configures SVGR to use custom Babel plugins for modifying generated JSX. This example demonstrates removing 'id' attributes, adding 'data-testid' and 'focusable', and replacing color values using specific SVGR Babel plugins. Requires SVGR and Babel plugins. ```javascript // svgr.config.js - Custom Babel transformations module.exports = { plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'], jsx: { babelConfig: { plugins: [ // Remove id attribute from svg element [ '@svgr/babel-plugin-remove-jsx-attribute', { elements: ['svg'], attributes: ['id'], }, ], // Add custom attributes [ '@svgr/babel-plugin-add-jsx-attribute', { elements: ['svg'], attributes: [ { name: 'data-testid', value: 'svg-icon' }, { name: 'focusable', value: 'false', literal: true }, ], }, ], // Replace attribute values [ '@svgr/babel-plugin-replace-jsx-attribute-value', { values: [ { value: '#000', newValue: 'currentColor' }, { value: '#fff', newValue: 'props.secondaryColor', literal: true }, ], }, ], ], }, }, } // Available SVGR Babel plugins: // @svgr/babel-plugin-add-jsx-attribute // @svgr/babel-plugin-remove-jsx-attribute // @svgr/babel-plugin-remove-jsx-empty-expression // @svgr/babel-plugin-replace-jsx-attribute-value // @svgr/babel-plugin-svg-dynamic-title // @svgr/babel-plugin-svg-em-dimensions // @svgr/babel-plugin-transform-react-native-svg // @svgr/babel-plugin-transform-svg-component ``` -------------------------------- ### Basic Webpack Configuration Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Configure webpack.config.js to use @svgr/webpack for processing SVG files. ```APIDOC ## Basic Webpack Configuration ### Description Configure webpack.config.js to use @svgr/webpack for processing SVG files. ### File `webpack.config.js` ### Code ```javascript module.exports = { module: { rules: [ { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }, ], }, } ``` ### Usage in Code ```javascript import Star from './star.svg' const Example = () => (
) ``` ``` -------------------------------- ### SVG to React Component Transformation with SVGR Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/what-is-svgr.mdx This example demonstrates how SVGR transforms a raw SVG XML structure into a functional React component. The process involves optimizing the SVG, converting it to JSX, and wrapping it in a React component structure. The output is a reusable React component that accepts standard SVG props. ```xml Rectangle 5 Created with Sketch. ``` ```javascript import * as React from 'react' const SvgComponent = (props) => ( ) export default SvgComponent ``` -------------------------------- ### Configure package.json Scripts for SVGR in Remix Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/remix.mdx Sets up npm scripts in package.json to automate the conversion of SVG files into React components using SVGR, including tasks for initial conversion, watching for changes, and integrating with Remix development server. ```json { "scripts": { "icons": "npx @svgr/cli --out-dir app/components/icons -- app/icons", "icons:watch": "npm-watch icons", "dev:svg": "run-s icons icons:watch", "dev:remix": "remix dev", "dev": "run-p dev:*" }, "watch": { "icons": { "patterns": [ "icons" ], "extensions": "svg", "quiet": false } } } ``` -------------------------------- ### Handle Mixed SVG Assets and Components Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Using resourceQuery to differentiate between SVG files treated as URLs and those treated as React components. ```javascript module.exports = { module: { rules: [ { test: /\.svg$/i, type: 'asset', resourceQuery: /url/, }, { test: /\.svg$/i, issuer: /\.[jt]sx?$/, resourceQuery: { not: [/url/] }, use: ['@svgr/webpack'], }, ], }, } ``` -------------------------------- ### Transform SVG Files via CLI Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/cli.mdx Demonstrates transforming a single SVG file from a file path, standard input, or redirecting output to a specific file. ```bash npx @svgr/cli -- icons/clock-icon.svg npx @svgr/cli < icons/clock-icon.svg npx @svgr/cli -- icons/clock-icon.svg > dist/ClockIcon.js ``` -------------------------------- ### Clone and Branch Repository (Shell) Source: https://github.com/gregberge/svgr/blob/main/CONTRIBUTING.md This snippet shows how to clone the SVGR repository and create a new branch for your contributions using Git commands. ```sh git clone https://github.com//svgr cd svgr git checkout -b my_branch ``` -------------------------------- ### Import and Use SVG as React Component Source: https://github.com/gregberge/svgr/blob/main/packages/rollup/README.md Demonstrates how to import an SVG file after configuring @svgr/rollup and render it as a React component. ```javascript import Star from './star.svg' const App = () => (
) ``` -------------------------------- ### Configure SVGR with .svgrrc Source: https://github.com/gregberge/svgr/blob/main/packages/plugin-jsx/README.md Enable the JSX plugin by adding it to the plugins array in your .svgrrc configuration file. ```json { "plugins": ["@svgr/plugin-jsx"] } ``` -------------------------------- ### Synchronous Transformation Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Explains how to use the synchronous `transform.sync` method for environments where asynchronous operations are not suitable. ```APIDOC ## Synchronous Usage SVGR provides both asynchronous and synchronous APIs. The synchronous API, `transform.sync`, is available for use cases where asynchronous operations are not feasible. ### Parameters The parameters for `transform.sync` are the same as the asynchronous `transform` function: `source`, `options`, and `state`. ### Request Example ```js import { transform } from '@svgr/core' const svgCode = ` ` const jsCode = transform.sync( svgCode, { icon: true }, { componentName: 'MyComponent' }, ) console.log(jsCode) ``` ``` -------------------------------- ### Babel Plugin Configuration Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-add-jsx-attribute/README.md Configuration details for adding attributes to JSX elements via the .babelrc file. ```APIDOC ## Configuration: @svgr/babel-plugin-add-jsx-attribute ### Description This plugin allows you to inject specific attributes into JSX elements during compilation. It is useful for adding default props or accessibility attributes to SVG components. ### Parameters #### Plugin Options - **elements** (array) - Required - A list of element names (e.g., ['svg']) to target. - **attributes** (array) - Required - A list of attribute objects to inject. - **name** (string) - Required - The name of the attribute. - **value** (string) - Required - The value of the attribute. - **spread** (boolean) - Optional - Whether to use spread syntax. - **literal** (boolean) - Optional - Whether the value is a literal expression. - **position** (string) - Optional - The position to insert the attribute ('start' or 'end'). ### Configuration Example ```json { "plugins": [ [ "@svgr/babel-plugin-add-jsx-attribute", { "elements": ["svg"], "attributes": [ { "name": "width", "value": "200", "spread": false, "literal": false, "position": "end" } ] } ] ] } ``` ``` -------------------------------- ### Configure @svgr/rollup Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/rollup.mdx How to initialize and configure the SVGR plugin within your rollup.config.js file. ```APIDOC ## Rollup Plugin Configuration ### Description Integrate SVGR into your Rollup build process to enable importing SVG files directly as React components. ### Method N/A (Build-time configuration) ### Endpoint rollup.config.js ### Parameters #### Request Body - **icon** (boolean) - Optional - If true, sets width and height to 1em. - **babel** (boolean) - Optional - Set to false to disable default Babel transformations. - **exportType** (string) - Optional - Set to 'named' to force named exports. - **namedExport** (string) - Optional - Customize the name of the exported component. ### Request Example ```js import svgr from '@svgr/rollup' export default { plugins: [svgr({ icon: true, babel: true })], input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs' } } ``` ### Response #### Success Response (Build Output) - **Bundle** (file) - Transformed JavaScript bundle containing React components generated from SVGs. ``` -------------------------------- ### Configure SVGR Loader Options Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Passing configuration options like 'icon: true' directly to the @svgr/webpack loader in the Webpack config. ```javascript module.exports = { module: { rules: [ { test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: [{ loader: '@svgr/webpack', options: { icon: true } }], }, ], }, } ``` -------------------------------- ### Configure Babel plugin Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-remove-jsx-empty-expression/README.md Add the plugin to your .babelrc configuration file to enable the removal of empty JSX expressions. ```json { "plugins": ["@svgr/babel-plugin-remove-jsx-empty-expression"] } ``` -------------------------------- ### Import SVG as URL and React Component Source: https://github.com/gregberge/svgr/blob/main/packages/rollup/README.md Shows how to import an SVG to use as an image source URL and also as a React component when using the url and @svgr/rollup plugins together. ```javascript import starUrl, { ReactComponent as Star } from './star.svg' const App = () => (
star
) ``` -------------------------------- ### Configure SVGO Options Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/options.mdx Allows specifying custom SVGO configuration to further optimize SVG code. This can be done through the CLI or API, referencing SVGO's extensive options. ```bash svgr --svgo-config '{"plugins": ["removeViewBox"]}' input.svg --out-dir src ``` ```javascript import svgr from '@svgr/core'; const svgCode = '...'; svgr(svgCode, { svgoConfig: { plugins: [ 'removeViewBox' ] } }, { componentName: 'MyComponent' }).then(component => { console.log(component); }); ``` -------------------------------- ### Asynchronous Transformation Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Demonstrates how to use the asynchronous `transform` function to convert SVG code into a JavaScript component. ```APIDOC ## Asynchronous Usage Import `transform` from `@svgr/core` to transform a file. It takes three arguments: `source`, `options`, and `state`. ### Parameters #### `source` (string) The SVG source code to transform. #### `options` (object) The options used to transform the SVG. Refer to [SVGR options reference](https://react-svgr.com/docs/options/) for available options. #### `state` (object) A state linked to the transformation. It has two main properties: - `componentName` (required): The name of the component that will be used in the generated component. - `filePath` (required): The name of the file that is generated, mainly used to find runtime config file to apply. ### Request Example ```js import { transform } from '@svgr/core' const svgCode = ` ` const jsCode = await transform( svgCode, { icon: true }, { componentName: 'MyComponent' }, ) console.log(jsCode) ``` ### Response Example ```js // Example output (actual output may vary based on options) import * as React from "react" function MyComponent(props) { return React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", xmlnsXlink: "http://www.w3.org/1999/xlink", ...props, }, React.createElement("rect", { x: "10", y: "10", height: "100", width: "100", style: "stroke:#ff0000; fill: #0000ff", })) } export default MyComponent ``` ``` -------------------------------- ### Mock SVG File for Jest Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/jest.mdx Creates a mock file for SVG imports in Jest. It exports a default URL and a ReactComponent, supporting various import syntaxes. ```jsx export default 'SvgrURL' export const ReactComponent = 'div' ``` -------------------------------- ### Transform SVG to React Component via CLI Source: https://github.com/gregberge/svgr/blob/main/README.md Demonstrates the command line usage of SVGR to convert an icon SVG file into a React component. It includes flags to replace specific attribute values with 'currentColor' for better styling control. ```shell npx @svgr/cli --icon --replace-attr-values "#063855=currentColor" -- icon.svg ``` -------------------------------- ### Configure Babel for React Native SVG Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-transform-react-native-svg/README.md Add the plugin to your .babelrc configuration file to enable the transformation. ```json { "plugins": ["@svgr/babel-plugin-transform-react-native-svg"] } ``` -------------------------------- ### Configure Babel for SVG Dynamic Title Source: https://github.com/gregberge/svgr/blob/main/packages/babel-plugin-svg-dynamic-title/README.md Add the plugin to your .babelrc configuration file to enable dynamic title and description support in SVGR transformations. ```json { "plugins": ["@svgr/babel-plugin-svg-dynamic-title"] } ``` -------------------------------- ### Create custom SVGR component templates Source: https://context7.com/gregberge/svgr/llms.txt Shows how to define custom templates using tagged template literals to manipulate the generated React component structure. These templates can be used via the CLI or within the configuration object. ```javascript const template = ({ imports, interfaces, componentName, props, jsx, exports }, { tpl }) => { return tpl` ${imports} import PropTypes from 'prop-types'; ${interfaces} function ${componentName}(${props}) { return ${jsx}; } ${componentName}.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; ${exports} ` } module.exports = template ``` -------------------------------- ### Import and Use SVG as React Component in Remix Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/remix.mdx Demonstrates how to import an SVG file as a React component after it has been processed by SVGR and use it within a Remix application. ```javascript import Star from '~/icons/star.svg' const Example = () => (
) ``` -------------------------------- ### Transform SVG to React Component (Sync) Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/node-api.mdx Illustrates the synchronous transformation of SVG code into a React component using `transform.sync`. This method is suitable when asynchronous operations are not feasible. ```javascript import { transform } from '@svgr/core' const svgCode = ` ` const jsCode = transform.sync( svgCode, { icon: true }, { componentName: 'MyComponent' }, ) ``` -------------------------------- ### Using Custom Babel Configuration Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/webpack.mdx Instructions on how to disable SVGR's default Babel transformation to use a custom Babel configuration. ```APIDOC ## Use your own Babel configuration ### Description By default, `@svgr/webpack` includes an optimized `babel-loader` configuration. If you need to use a custom Babel setup (e.g., for Preact), you can disable SVGR's built-in Babel transformation by setting `babel: false` in the loader options. ### Example Webpack Configuration (with Preact) ```javascript { test: /\.svg$/, use: [ { loader: 'babel-loader', options: { presets: ['preact', 'env'], }, }, { loader: '@svgr/webpack', options: { babel: false }, } ], } ``` ``` -------------------------------- ### Transform SVG Directories Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/cli.mdx Commands for batch processing directories, including options for ignoring existing files, changing filename casing, and managing index generation. ```bash npx @svgr/cli --out-dir dist -- icons npx @svgr/cli --out-dir dist --ignore-existing -- icons npx @svgr/cli --out-dir dist --filename-case kebab -- icons npx @svgr/cli --out-dir dist --no-index -- icons ``` -------------------------------- ### Transform HAST to Babel AST Source: https://github.com/gregberge/svgr/blob/main/packages/hast-util-to-babel-ast/README.md Demonstrates how to parse an SVG string into a HAST tree and convert it into a Babel AST using the library's default export. ```javascript import { parse } from 'svg-parser' import hastToBabelAst from '@svgr/hast-util-to-babel-ast' const hastTree = parse(``) const babelTree = hastToBabelAst(hastTree) ``` -------------------------------- ### Custom SVGR Index Templates (JavaScript) Source: https://context7.com/gregberge/svgr/llms.txt Defines two JavaScript templates for generating custom index.js files when transforming directories with SVGR. The first creates named exports, while the second generates an icon map object. It requires Node.js and the 'path' module. ```javascript // index-template.js - Basic index with named exports const path = require('path') function indexTemplate(filePaths) { const exportEntries = filePaths.map(({ path: filePath }) => { const basename = path.basename(filePath, path.extname(filePath)) const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename return `export { default as ${exportName} } from './${basename}'` }) return exportEntries.join('\n') } module.exports = indexTemplate ``` ```javascript // index-template-map.js - Index with icon map object const path = require('path') function indexTemplate(filePaths) { const entries = filePaths.map(({ path: filePath, originalPath }) => { const originalFileName = path.basename(originalPath, path.extname(originalPath)) const basename = path.basename(filePath, path.extname(filePath)) const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename const importLine = `import ${exportName} from './${basename}';` const mapKey = /.*[.-].*/.test(originalFileName) ? `'${originalFileName}'` : originalFileName return { importLine, mapLine: `${mapKey}: ${exportName}` } }) return `${entries.map(({ importLine }) => importLine).join('\n')} export const iconMap = { ${entries.map(({ mapLine }) => mapLine).join(',\n ')} }; export default iconMap; ` } module.exports = indexTemplate ``` -------------------------------- ### Configure Next.js for SVGR Source: https://github.com/gregberge/svgr/blob/main/website/pages/docs/next.mdx Configuration for next.config.js to handle SVG files via Webpack rules and Turbopack loaders. ```javascript import type { NextConfig } from "next"; const nextConfig: NextConfig = { webpack(config) { config.module.rules.push({ test: /\.svg$/, use: [ { loader: "@svgr/webpack", options: { icon: true, }, }, ], }); return config; }, turbopack: { rules: { "*.svg": { loaders: ["@svgr/webpack"], as: "*.js", }, }, } }; export default nextConfig; ```