首页 文章

在css中使用webpack的图像URL /路径?

提问于
浏览
1

我正在研究一个带有react和webpack的项目 . 我正在使用url loader插件来处理图像 . 如果我想将图像包含在img标记中,这可以正常工作 . 但我想在我的CSS中包含一个图像作为背景图像 . 即

const hero = require('../../images/landing-hero.jpg');

这将返回一个文件名,除了在我的CSS中以外,它在任

.hero {
  background-image: url('3b1425242c422b429f78f272b0a4c0f7.jpg');
  background-size: cover;
  position: relative;
  display: block;
  min-height: 101vh;
  color: white;
}

我尝试了一些路径的变化但没有成功 . 然而,做http://localhost:8080/3b1425242c422b429f78f272b0a4c0f7.jpg工作 . 如何在不进行整个网址的情况下将图像用作背景网址?这是我的webpack配置

'use strict';

/*=============================================>>>>>
= MODULES =
===============================================>>>>>*/

const path = require('path');
const webpack = require('webpack');
const WebpackNotifier = require('webpack-notifier');
// PostCSS
const autoprefixer = require('autoprefixer');

'use strict';

/*=============================================>>>>>
= MODULES =
===============================================>>>>>*/

const path = require('path');
const webpack = require('webpack');
const WebpackNotifier = require('webpack-notifier');
// PostCSS
const autoprefixer = require('autoprefixer');

/*= End of MODULES =*/
/*=============================================<<<<<*/

/*=============================================>>>>>
= WEBPACK CONFIG =
===============================================>>>>>*/

module.exports = {
  entry:   {
    app: path.resolve(`${__dirname}/src/client/public/app/main.tsx`)
  },
  output: {
    path:     path.resolve(`${__dirname}/build/client`),
    filename: 'public/zip/[name].bundle.js'
  },
  module: {
    loaders: [
      { test: /\.tsx$/, loader: 'babel!ts' },
      { test: /\.scss$/, loader: 'style!css?sourceMap!postcss!sass?sourceMap' },
      { test: /\.css$/, loader: 'style!css?sourceMap!postcss'},
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'}
    ]
  },
  postcss: function() {
    return [ autoprefixer ];
  },
  ts: {
    silent: true
  },
  plugins: [
    new WebpackNotifier({ title: 'Webpack', alwaysNotify: true }),
    new webpack.optimize.OccurenceOrderPlugin(),
  ]
};

/*= End of WEBPACK CONFIG =*/
/*=============================================<<<<<*/

我已尝试使用resolve-url-loader提供的解决方案here但是我没有看到其他类似的问题而没有运气这么抱歉,如果这感觉就像被问到了

1 回答

  • 3

    根据this issue,启用 sourcemap 时,它将使用blob为您的页面上的css提供服务 . 这会导致问题,因为背景 url() 是相对于css的,因此在blob中找不到文件,因此无法渲染图像 .

    它有几种方法可以解决此问题:

    • 使用 DataUrl ,查看url-loader,相应地设置 limit

    • 如果您的图片文件很大并且您不想使用数据网址,则可以将 output.publicPath 设置为您的网址 . 例如,通常在本地开发模式中, http://localhost:3000/ . 但是,这种解决方法并不完美,尤其是在您实施HTTPS时 . 您仍然可以编写一些简单的代码来相应地调整此值 .

相关问题