首页 > 解决方案 > 在 Next JS 中将图像导入我的 CSS(SASS) 文件

问题描述

我对 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);

当我在 Google Chrome 和 Firefox 中打开 URL 时,什么都没有显示(img 未加载);

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

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

标签: reactjswebpacknext.js

解决方案


我刚刚找到了解决方案,我使用了 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

推荐阅读