gpt4 book ai didi

javascript - 使用从头开始构建的 webpack 的 react 应用程序未在 css 中加载图像

转载 作者:行者123 更新时间:2023-11-28 19:10:26 26 4
gpt4 key购买 nike

我使用 webpack 和 babel 构建了一个简单的 React 应用程序。我在加载图像时遇到问题。我的基本文件夹结构:

root: 
webpack.config.js
package.json

public:
index.html

src:
800x600-1x2x.jpg
App.css
App.js
index.js

App.js 是样板代码:

import React, { Component} from "react";
import {hot} from "react-hot-loader";
import "./App.css";

class App extends Component{
render(){
return(
<div className="App">
<h1> Hello, World!! </h1>
</div>
);
}
}

export default hot(module)(App);

App.css 是我将图像加载到背景中的地方:

.App {
margin: 1rem;
font-family: Arial, Helvetica, sans-serif;
background-image: url("./800x600-1x2x.jpg");
border: 1px solid red;
}

webpack.config.js:我试过使用 url-loader 而不是 file-loader,但是没有用

const path = require("path");
const webpack = require("webpack");

module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["@babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: "file-loader"
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};

如果我点击 800x600-1x2x.jpg,通过 chrome 源我可以看到 webpack://正在对图像做一些事情我得到这个代码:

__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = (__webpack_require__.p + "0e5cf6190f4b1586fb587bc9e9577981.jpg");

选择 App 元素并查看 css 规则,我看到这个被划掉了:

background-image: url([object Module]);

我尝试过但没有奏效的事情:

将图像放在没有做任何事情的公用文件夹中。

创建 dist 文件夹并将图像放入该文件夹。

安装 html-loader 并将其包含在 webpack 中:

  {
test: /\.html$/,
loader: 'html-loader'
},

安装 resolve-url-loader 并将其包含在 webpack 中:

  {
test: /\.css$/,
loader: ["style-loader", "css-loader", "resolve-url-loader"]
},

其他信息:

我也没有构建 webpack 在运行时编译的 bundle.js。

我正在使用它来运行我的 webpack:webpack-dev-server --mode development

我查看了其他 stackoverflow 答案,但没有发现任何对我有用的答案。我错过了什么?

最佳答案

看起来相对路径不正确。您的资源应放在源文件夹中,而不是根目录中。

这个结构应该适用于你当前的 webpack 配置

root: 
webpack.config.js
package.json


public:
index.html

src:
index.js
800x600-1x2x.jpg
App.css
App.js

关于javascript - 使用从头开始构建的 webpack 的 react 应用程序未在 css 中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com