如何在 Webpack 中使用 css 中的图像 [英] How to use images in css with Webpack

查看:26
本文介绍了如何在 Webpack 中使用 css 中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Webpack 设置进行 React,并且正在努力做看起来应该很简单的任务.我希望 webpack 包含图像,并像使用 gulp 一样将它们最小化,但我无法弄清楚.我只是希望能够像这样在我的 css 中链接图像:

I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can't figure it out. I just want to be able to link an image in my css like so:

/* ./src/img/background.jpg */

body { background: url('./img/background.jpg'); }

我的所有 css/js/img 文件夹都在 src 文件夹中.Webpack 输出到 dist 文件夹,但我不知道如何在那里获取图像.

I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can't figure out how to get images there.

这是我的 webpack 设置:

Here is my webpack setup:

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

 module.exports = {
  devtool: 'cheap-eval-source-map',
  entry: [
   'webpack-dev-server/client?http://localhost:8080',
   'webpack/hot/dev-server',
   './src/index.js'
  ],
  output: {
  path: path.join(__dirname, 'dist'),
  //  publicPath: './dist',
  filename: 'bundle.js'
  },
  plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new HtmlWebpackPlugin({
  template: './src/index.html'
   })
  ],
  module: {
  loaders: [{
   exclude: /node_modules/,
   test: /.js?$/,
   loader: 'babel'
   }, {
  test: /.scss$/,
  loader: 'style!css!sass'
    }, {
  test: /.(png|jpg)$/,
  loader: 'file-loader'
  }]
 },

 devServer: {
  historyApiFallback: true,
  contentBase: './dist',
  hot: true
  }
};

推荐答案

我遇到了类似的问题,发现你可以使用 url-loader 将 CSS 中的 "url()" 语句解析为任何其他 require 或 import 语句.

I was stuck with similar issue and found that you can use url-loader to resolve "url()" statements in your CSS as any other require or import statements.

安装:

npm install url-loader --save-dev

它将安装可以将解析路径转换为 ​​BASE64 字符串的加载程序.

It will install the loader that can convert resolved paths as BASE64 strings.

在你的 webpack 配置文件中使用 url-loader in loaders

In your webpack config file use url-loader in loaders

{
  test: /.(png|jpg)$/,
  loader: 'url-loader'
}

还要确保您正确指定了公共路径和要加载的图像的路径.

Also make sure that you are specifying your public path correctly and path of images you are trying to load.

这篇关于如何在 Webpack 中使用 css 中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆