【问题标题】:Importing SVG in NextJS在 NextJS 中导入 SVG
【发布时间】:2020-07-10 18:16:51
【问题描述】:

我试图在 NextJS 项目中导入一个 svg,每次我收到这个错误

./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.org/concepts#loaders
> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/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="

我尝试过使用 next-images 和 svgr。我将在下面粘贴我的 About.js 代码,如果有人能告诉我我做错了什么,那就太好了。

import LayoutNoLogo from '../comps/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;

【问题讨论】:

  • @sv12 我跟着这个,它仍然出现同样的错误
  • 你也可以发布你的 svg.js 吗?
  • export default () =&gt; &lt;div&gt; &lt;img src={require('../assets/aboutimg.svg')} /&gt; &lt;/div&gt;

标签: javascript reactjs next.js


【解决方案1】:

我终于在我的项目中使用了file-loader 来使用 SVG 图像。

  1. 安装 webpack 和文件加载器:yarn add webpack, yarn add file-loader -D
  2. 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. 现在我可以使用import img from '../assets/image.svg'

【讨论】:

    【解决方案2】:

    使用 next-images 并添加正确的模块导出允许我使用所有文件类型的图像。

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

    【讨论】:

    • next next 9^
    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 2020-10-23
    • 2020-06-26
    • 1970-01-01
    • 2022-12-02
    • 2021-12-29
    • 2019-05-28
    • 2020-04-20
    相关资源
    最近更新 更多