Can't import SVG into Next.js

前端 未结 6 1714
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 07:39

When I try to import SVG Image then the following error shows. Which loader I have to use for importing SVG images?

./static/Rolling-1s-200px.svg 1:0
Module          


        
6条回答
  •  忘掉有多难
    2020-12-09 08:22

    I personally prefer next-react-svg plugin which allows to treat SVG images as React components and automatically inline them, similar to what Create React App does.

    Here is how to use it:

    1. Install next-react-svg:
    npm i next-react-svg
    
    1. Add necessary settings to next.config.js:
    const withReactSvg = require('next-react-svg')
    const path = require('path')
    
    module.exports = withReactSvg({
      include: path.resolve(__dirname, 'src/assets/svg'),
      webpack(config, options) {
        return config
      }
    })
    

    The include parameter is compulsory and it points to your SVG image folder.

    If you already have any plugins enabled for your Next.js, consider using next-compose-plugins to properly combine them.

    1. Import your SVGs as ordinary React components:
    import Logo from 'assets/svg/Logo.svg';
    
    export default () => (
      
    );
    

    That's it. From now on, Next.js will be including SVG images imported this way into the rendered markup as SVG tags.

提交回复
热议问题