【问题标题】:Importing images to my CSS(SASS) file in Next JS在 Next JS 中将图像导入我的 CSS(SASS) 文件
【发布时间】:2020-01-05 13:17:30
【问题描述】:

我是 javascript 框架和 webpack 的新手,我只是想在我的 css 文件中导入图像。

这就是我的项目结构;

那是我的 next.config.js;

// next.config.js
const withCSS = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');

module.exports = withCSS( withSass( withImages({
    webpack (config, options) {
        config.module.rules.push({
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            use: {
                loader: 'url-loader',
                options: {
                    limit: 100000
                }
            }
        });
        return config
    }
})));

Main.scss 文件;

$font-type: 'Open Sans', sans-serif;
$primary-color: #ff5e1f;

body {
    font-family: $font-type;

    header {
        float: left;
        width: 100%;
        min-height: 100px;

        a.logo {
            float: left;
            width: 200px;
            height: 100px;
            background: url('../images/logo.png');
        }
    }
}

我只是在尝试使用我的徽标,终端没有任何问题;

但是当我访问我的网站和开发者工具时,网址是这样的;

background: url(/_next/static/images/logo-ea62a25….png);

当我在谷歌浏览器和 Firefox 中打开 URL 时,什么都没有显示(img 未加载);

The image "http://localhost:3000/_next/static/images/logo-ea62a2595859a68f77a6cc473535b8f5.png" canot be displayed because it contains errors.

也许这是一个愚蠢的问题,很抱歉,但我无法处理它:/ 我该如何解决这个问题?

【问题讨论】:

    标签: reactjs webpack next.js


    【解决方案1】:

    我刚刚找到了解决方案,我使用了 file-loader 而不是 url-loader。

    我像这样更改了我的 next.config.js 文件;

    // next.config.js
    const withCSS = require('@zeit/next-css');
    const withSass = require('@zeit/next-sass');
    const withImages = require('next-images');
    
    module.exports = withCSS( withSass( withImages({
        module: {
            rules: [
                {
                    test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/i,
                    use: [
                        {
                            loader: 'file-loader',
                        },
                    ],
                },
            ],
        },
    })));
    

    它有效:) (也别忘了用 npm 安装文件加载器)

    npm install file-loader --save-dev
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2017-12-24
      • 1970-01-01
      • 2020-08-27
      • 2020-02-13
      • 2022-06-14
      • 2011-10-01
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多