简体   繁体   English

使用从头开始构建的 webpack 反应应用程序不会在 css 中加载图像

[英]react app with webpack built from scratch is not loading an image in css

I built a simple react app that uses webpack and babel.我构建了一个使用 webpack 和 babel 的简单 React 应用程序。 I am having trouble loading my images.我在加载图片时遇到问题。 My basic folder structure:我的基本文件夹结构:

root: 
  webpack.config.js
  package.json

  public:
    index.html

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

App.js is boilerplate code: 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 is where I am loading an image into my background: App.css 是我将图像加载到我的背景的地方:

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

webpack.config.js: i've tried using url-loader instead of file-loader that did not work 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()]
};

Looking through chrome sources I can see webpack:// is doing something with the image if I click on the 800x600-1x2x.jpg I get this code:查看 chrome 源,如果我点击 800x600-1x2x.jpg 我可以看到 webpack:// 正在对图像做一些事情我得到这个代码:

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

Selecting App element and looking at the css rules I see this crossed out:选择 App 元素并查看 css 规则,我看到这被划掉了:

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

Things that I tried and did not work:我尝试过但没有奏效的事情:

placing the image in the public folder that didn't do anything.将图像放在没有做任何事情的公共文件夹中。

creating a dist folder and putting the image in that folder.创建一个 dist 文件夹并将图像放在该文件夹中。

installed html-loader and included it in webpack:安装 html-loader 并将其包含在 webpack 中:

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

installed resolve-url-loader and included it in webpack:安装了 resolve-url-loader 并将其包含在 webpack 中:

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

Other info:其他信息:

I am also not building a bundle.js the webpack is compiling at runtime.我也没有构建 webpack 在运行时编译的 bundle.js。

I am using this to run my webpack: webpack-dev-server --mode development我正在使用它来运行我的 webpack: webpack-dev-server --mode development

I looked around other stackoverflow answers and didn't see anything that worked for me.我环顾了其他 stackoverflow 答案,没有看到任何对我有用的东西。 What am I missing?我错过了什么?

It looks like the relative paths are incorrect.看起来相对路径不正确。 Your assets should be placed inside your source folder, not in the root.您的资产应该放在源文件夹中,而不是根目录中。

This structure should work with your current webpack config这个结构应该适用于你当前的 webpack 配置

root: 
  webpack.config.js
  package.json


  public:
    index.html

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

So I dug deep in webpacks documentation and other online projects for a whole day yesterday only to realize that my dependencies were out of date... However all the effort I put in was not a lost cause, I created a much better and cleaner set up that will work with a react app and load css and images.所以昨天我在 webpacks 文档和其他在线项目中深挖了一整天才意识到我的依赖已经过时了......但是我付出的所有努力都没有失败,我创造了一个更好更干净的集合up 将与反应应用程序一起使用并加载 css 和图像。 Enjoy.享受。 -.- -.-

package.json:包.json:

  "devDependencies": {
    "@babel/cli": "^7.1.0",
    "@babel/core": "^7.1.0",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.2",
    "css-loader": "^3.4.0",
    "file-loader": "^5.0.2",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^1.1.1",
    "url-loader": "^3.0.0",
    "webpack": "^4.41.4",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.10.1"
  },
  "dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.3.11"
  }

folder structure:文件夹结构:

public
  800x600-1x2x.jpg
  index.html

src
  App.css
  App.js
  index.js

webpack.config.js: webpack.config.js:

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "/"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: { presets: ["@babel/env"] }
      },
      {
        test: /\.css$/,
        loader: ["style-loader", "css-loader"]
      },
      {
        test: /\.(jpg)$/i,
        loader: "url-loader"
      }
    ]
  },
  devServer: {
    hot: true,
    open: true,
    port: 3000,
    proxy: {"/": "http://localhost:5000"},
    contentBase: path.resolve(__dirname, "public"),
    publicPath: "/"
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, 'public/index.html'),
        inject: true
    })
  ]
};

To make a css file work one has to import it inside your .js Example my index.js:要使 css 文件工作,必须将其导入到您的 .js 中,例如我的 index.js:

import "./App.css"
import App from "./App.js"
ReactDOM.render(<App/>, document.getElementById("root"));

From there my css file loads an image through my directory path:从那里我的 css 文件通过我的目录路径加载一个图像:

background: url("../public/800x600-1x2x.jpg");

Loading an image in html through the img tag is as usual(warning below):像往常一样通过 img 标签加载 html 中的图像(警告如下):

<img src="800x600-1x2x.jpg">

Warning: the img tag wont load an image when using a proxy with no real backend.警告:当使用没有真正后端的代理时,img 标签不会加载图像。

However, we are using react components so we can/should load an image inside our components jsx.但是,我们正在使用 react 组件,因此我们可以/应该在组件 jsx 中加载图像。

First import the image and then use the image tag.首先导入图像,然后使用图像标签。 Example:例子:

import background from '../public/800x600-1x2x.jpg'

const App = () => <img src={background}></img>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM