javascript - react : setting background image for a file present on the server

标签 javascript css reactjs sass next.js

我想为我使用 React 构建的网站使用背景图片。

我在 .scss 文件中包含:

html {  
    background-color: #FFFCB2;
    background-image: url(https://mdn.mozillademos.org/files/11991/startransparent.gif);
}

我只是在我的 index.jsx 主页中导入 .scss 文件:

import "styles/index.scss"

而且效果很好

但是当我使用保存在文件夹中的相同图像时,如下所示:

html {  
    background-color: #FFFCB2;
    background-image: url(../static/images/startransparent.gif);
}

我在网络客户端中收到以下错误消息:

./styles/index.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleParseError: Module parse failed: Unexpected character '' (1:6)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)

大多数对此错误消息的引用(如 this 帖子中)指的是在我的 webpack.config 中包含一系列指令。

但是我的主要架构中没有 webpack.config,我使用的是 babel(我不确定这两个事实是如何联系的,我不精通 JS)。所以我不知道在哪里应用它。

如何从本地正确加载图片?如果我的元素中没有 webpack.config 文件怎么办?

**编辑:似乎我缺少 webpack.config 是因为我正在使用 next。 **

我当前的 next.config.js 文件:

const withTranspileModules = require("next-transpile-modules")
const withTypescript = require("@zeit/next-typescript")
const withSass = require("@zeit/next-sass")

const _ = require("lodash")

const config = {
    exportPathMap() {
        return {
            "/": { page: "/" },
        }
    },
    distDir: "build",
    transpileModules: ["@iconify/react"],
}

module.exports = _.flow([,withTranspileModules, withTypescript, withSass])(config)

最佳答案

请将此添加到您的 webpack 配置文件中。它可以解决 gif 加载器问题。请找到这个 link更多引用

  {
                test: /\.(ttf|eot|svg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                include: SRC,
                use: [{
                    loader: 'file-loader'
                }]
            }]
        },

关于javascript - react : setting background image for a file present on the server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56558368/

相关文章:

reactjs - Redux Saga - 无法取消任务

reactjs - 从构建 React.js 中排除 .js 文件

javascript - MVC 5 Bootstrap.v3.Datetimepicker.CSS 错误 : Object doesn't support property or method 'datetimepicker'

javascript - 阻止垂直滚动但允许水平滚动

javascript - 为什么我的列表在 React 中循环到不同的寡妇

html - 为什么我的背景不会重复 x 或拉伸(stretch)到全宽?

css - CSS3透视变换后如何找到元素的二维屏幕点

javascript - 如何访问在卸载前触发的 JavaScript href 事件

javascript - 同步服务器和客户端时间?

javascript - 如何确保 OAuth2 身份验证成功后重新发送原始 Google Chat 消息?