【问题标题】:react app with webpack built from scratch is not loading an image in css从头开始构建的带有 webpack 的反应应用程序不会在 css 中加载图像
【发布时间】:2020-04-13 05:04:36
【问题描述】:

我构建了一个使用 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 而不是文件加载器,但不起作用

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 我可以看到 webpack:// 正在对图像进行处理,我可以通过 chrome 源代码查看此代码:

__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 答案,但没有发现任何对我有用的东西。我错过了什么?

【问题讨论】:

    标签: javascript css reactjs webpack


    【解决方案1】:

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

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

    root: 
      webpack.config.js
      package.json
    
    
      public:
        index.html
    
      src:
        index.js
        800x600-1x2x.jpg
        App.css
        App.js
    

    【讨论】:

    • 我把app.css、app.js和图片放到src文件夹下。没用。
    • 我认为将 contentBase 设置为 public 会让人感到困惑,而所有已编译的文件都在 dist 中。您可以尝试使用 html-loader 来处理 index.html
    • 安装了 html-loader 并添加了,{ test: /\.html$/, loader: 'html-loader' },没有用。
    【解决方案2】:

    所以我昨天在 webpacks 文档和其他在线项目中深入挖掘了一整天,结果发现我的依赖项已经过时了……但是我付出的所有努力都不是徒劳的,我创造了一个更好的和更清洁的设置将与反应应用程序一起使用并加载 css 和图像。享受。 -.-

    package.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"
      }
    

    文件夹结构:

    public
      800x600-1x2x.jpg
      index.html
    
    src
      App.css
      App.js
      index.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
        })
      ]
    };
    

    要使 css 文件正常工作,必须将其导入到您的 .js 中 以我的 index.js 为例:

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

    从那里我的 css 文件通过我的目录路径加载图像:

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

    通过img标签在html中加载图片和往常一样(警告如下):

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

    警告:使用没有真正后端的代理时,img 标签不会加载图像。

    但是,我们正在使用 react 组件,因此我们可以/应该在我们的组件 jsx 中加载图像。

    先导入图片,再使用图片标签。示例:

    import background from '../public/800x600-1x2x.jpg'
    
    const App = () => <img src={background}></img>
    

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2022-07-24
      • 1970-01-01
      • 2022-09-23
      相关资源
      最近更新 更多