Home > Mobile >  Import .svg and resize .svg use styled-components in next.js
Import .svg and resize .svg use styled-components in next.js

Time:03-02

I am currently trying import .svg into next.js project but I failed.

I tried import .svg same way as in react project, that I created typing.d.ts and import svg like component. But it doesn't work.

declare module '*.svg' {
  import React from 'react';

  const src: string;

  export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  export default src;
}

Import svg example

What I need?

  • Import .svg file and change its width and height.

Has anyone had the same problem? Or did anyone manage to solve it?

Thank you

CodePudding user response:

Maybe a solution.

  • Default option in next.js for removeViewBox is true. If you change in .svg height or width the view-box from .svg will be rest to default value.
  • If you use in your next.config.js webpack and set removeViewBox to false .svg resize start work.

A working example: stackblitz-resize-svg-next.js

  webpack(config) {
    config.module.rules.push({
      loader: '@svgr/webpack',
      options: {
        prettier: false,
        svgo: true,
        svgoConfig: {
          plugins: [
            {
              name: 'preset-default',
              params: {
                overrides: { removeViewBox: false },
              },
            },
          ],
        },
        titleProp: true,
      },
      test: /\.svg$/,
    });

    return config;
  },

If you have in .babelrc set "inline-react-svg" this solution will not work.

CodePudding user response:

Another approach I've used, leverages svgo-loader:

  // Asset handling
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {

    // SVG handler, inlines everything under 200KB
    config.module.rules.push({
      test: /\.svg$/,
      type: 'asset',
      parser: {
        dataUrlCondition: {
          maxSize: 200 * 1024
        }
      },
      use: 'svgo-loader'
    });
    
    return config;
  },
  • Related