我想为我使用 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/