最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Importing SVG in NextJS - Stack Overflow

programmeradmin3浏览0评论

I am trying to import an svg within a NextJS project, everytime I get this error

./assets/aboutimg.svg 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See 
> <svg xmlns="" xmlns:xlink="" width="578" height="1028" viewBox="0 0 578 1028">
|   <image id="_64538565_2370063099695596_8091233071539421184_n" data-name="64538565_2370063099695596_8091233071539421184_n" width="578" height="1028" xlink:href="

I have tried using next-images and also svgr. I will paste my About.js code below, it would be excellent if someone could let me know what I have been doing wrong.

import LayoutNoLogo from '../ps/LayoutNoLogo'
import AboutImg from '../assets/aboutimg.svg'

const About = () => {
    return (
        <LayoutNoLogo>
            <div className="row">
                <div className="column-1">
                    <img src={AboutImg} />
                </div>
                <div className="column-2">
                    <h1>About</h1>
                </div>
            </div>
            <style jsx>{`

        `}</style>

        </LayoutNoLogo>
    )
}

export default About;

I am trying to import an svg within a NextJS project, everytime I get this error

./assets/aboutimg.svg 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js/concepts#loaders
> <svg xmlns="http://www.w3/2000/svg" xmlns:xlink="http://www.w3/1999/xlink" width="578" height="1028" viewBox="0 0 578 1028">
|   <image id="_64538565_2370063099695596_8091233071539421184_n" data-name="64538565_2370063099695596_8091233071539421184_n" width="578" height="1028" xlink:href="

I have tried using next-images and also svgr. I will paste my About.js code below, it would be excellent if someone could let me know what I have been doing wrong.

import LayoutNoLogo from '../ps/LayoutNoLogo'
import AboutImg from '../assets/aboutimg.svg'

const About = () => {
    return (
        <LayoutNoLogo>
            <div className="row">
                <div className="column-1">
                    <img src={AboutImg} />
                </div>
                <div className="column-2">
                    <h1>About</h1>
                </div>
            </div>
            <style jsx>{`

        `}</style>

        </LayoutNoLogo>
    )
}

export default About;
Share Improve this question asked Mar 30, 2020 at 11:26 Mac DevMac Dev 1032 gold badges3 silver badges12 bronze badges 4
  • stackoverflow./questions/55175445/… – joy08 Commented Mar 30, 2020 at 11:33
  • @sv12 I followed this and it still es up with the same error – Mac Dev Commented Mar 30, 2020 at 11:43
  • can you post your svg.js also? – iamhuynq Commented Mar 30, 2020 at 11:45
  • export default () => <div> <img src={require('../assets/aboutimg.svg')} /> </div> – Mac Dev Commented Mar 30, 2020 at 12:25
Add a ment  | 

3 Answers 3

Reset to default 3

I've finally used file-loader for using SVG images in my project.

  1. install webpack and file loader : yarn add webpack, yarn add file-loader -D
  2. in next.config.js:
module.exports = {
    //...other configs
    webpack: (config, {}) => {
        config.module.rules.push({
                test: [/\.svg$/, /\.woff$/],
                loader: 'file-loader',
                options: {
                    name: '[name].[hash:8].[ext]',
                    publicPath: `/_next/static/images/`, //specify the base path
                    outputPath: 'static/images', //and output path
                }
        })
    }
}
  1. Now I can use import img from '../assets/image.svg'

Using next-images and adding the correct module exports allowed me to use images of all file types.

https://www.npmjs./package/next-images

Solution testet with nextjs13

  1. Install loader: yarn add @svgr/webpack

  2. Update next.config.js

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

    return config;
  },

Check fill prop (attribute) (svg, path etc.) & replace all values with currentColor for extending current text color (from css). Also you can remove all fill props from child tags, and extend it from parent svg.

<svg ... fill="currentColor">
...
</svg>

css:

.icons-wrapper { color: red } /* fill all icons to red */

I prefer import icon dynamically in ponent:

type AvailableIcons =
  | 'facebook' // ./svg/facebook.svg
  | 'google';

interface IProps {
  name?: AvailableIcons;
  style?: React.CSSProperties;
  className?: string;
  width?: number;
  height?: number;
}

export const Icon = async ({ name, width, height, ...iconProps }: IProps) => {
  try {
    const Icon = await import(`./svg/${name}.svg`).then((icon) => icon.default); // lazy import
    return <Icon id={`svg-${name}`} width={width} height={height || width} {...iconProps} />;
  } catch (e) {
    return <>[Icon `{name}` not found!]</>;
  }
};

also you can import your svg ponent directly:

import Logo from './svg/logo.svg'

const YourTestComponent = () => <>
   ...
   <Logo /* override props */ />
   ...
</>
发布评论

评论列表(0)

  1. 暂无评论