无法将SVG导入Next JS? [英] Can't import SVG into Next JS?

查看:125
本文介绍了无法将SVG导入Next JS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试导入SVG图像时,将显示以下错误.导入SVG图像时必须使用哪个加载器?

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 parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000"><filter id="b"><feGaussianBlur stdDeviation="12" /></filter><path fill="#817c70" d="M0 0h2000v2000H0z"/><g filter="url(#b)" transform="translate(4 4) scale(7.8125)" fill-opacity=".5"><ellipse fill="#000210" rx="1" ry="1" transform="matrix(50.41098 -3.7951 11.14787 148.07886 107 194.6)"/><ellipse fill="#eee3bb" rx="1" ry="1" transform="matrix(-56.38179 17.684 -24.48514 -78.06584 205 110.1)"/><ellipse fill="#fff4bd" rx="1" ry="1" transform="matrix(35.40604 -5.49219 14.85017 95.73337 16.4 123.6)"/><ellipse fill="#79c7db" cx="21" cy="39" rx="65" ry="65"/><ellipse fill="#0c1320" cx="117" cy="38" rx="34" ry="47"/><ellipse fill="#5cb0cd" rx="1" ry="1" transform="matrix(-39.46201 77.24476 -54.56092 -27.87353 219.2 7.9)"/><path fill="#e57339" d="M271 159l-123-16 43 128z"/><ellipse fill="#47332f" cx="214" cy="237" rx="242" ry="19"/></g></svg>

推荐答案

您需要提供一个可处理SVG导入的webpack加载程序,其中著名的一个是

You need to provide a webpack loader that will handle SVG imports, one of the famous one is svgr.

为了配置它以便下次使用,您需要将loader的用法添加到您的next.config.js文件中,如下所示:

In order to configure it to work with next, you need to add to your next.config.js file the usage of the loader, like that:

// next.config.js

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      issuer: {
        test: /\.(js|ts)x?$/,
      },
      use: ['@svgr/webpack'],
    });

    return config;
  },
};

有关更多配置信息,请查看文档

For more config info, check out the docs.

别忘了,请先安装它:npm install @svgr/webpack

Don't forget to install it first: npm install@svgr/webpack

修改

我添加了issuer部分,该部分仅将这些svg严格限制为从js / ts文件导入的svg的组成部分. 这使您可以为从其他文件类型(例如.css)导入的svg配置其他行为

I've added issuer section which strict these svg as component only for svgs that are imported from js / ts files. This Allows you to configure other behaviour for svgs that are imported from other file types (such as .css)

这篇关于无法将SVG导入Next JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆