无法从CSS文件Webpack5加载背景图像

p8h8hvxi  于 2023-02-10  发布在  Webpack
关注(0)|答案(1)|浏览(138)

我尝试将图像作为背景放在div中,但它无法识别它,因为webpack将路径更改为http://localhost:8080/gaia.png,而不是http://localhost:8080/assets/images/gaia.png图像在标记中显示正确,但如果我想从CSS文件使用它,则无法加载。我确定问题出在文件路径,但我不知道如何修复它。

index.js

import './assets/style/style.css'
import './assets/images/gaia.png'
import './assets/fonts/CascadiaCode.ttf'

const fun = () => {
  console.log('hey')
}
fun();

webpack.config.js

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

module.exports = {
  mode: 'development',
  devtool: 'inline-source-map',
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src', 'index.html')
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: '[name][ext][query]',
          outputPath: 'assets/images/',
        },
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
          filename: '[name][ext][query]',
          outputPath: 'assets/fonts/',
        },
      },
    ],
  },
};

style.css

.container {
  width: 300px;
  height: 300px;
  background-image: url("../images/gaia.png");
  background-size: auto;
}
mutmk8jj

mutmk8jj1#

删除outputpath并将其设置为:

generator: {
         filename: 'assets/images/[hash][ext][query]'
       }
     }

相关问题