【问题标题】:Webpack inline CSS background imagesWebpack 内联 CSS 背景图片
【发布时间】:2016-10-27 09:55:00
【问题描述】:

我正在尝试让 webpack 加载图像,但似乎无法正常工作。我的配置如下:

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    publicPath: "/build/",
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?/,
        include: APP_DIR,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loaders: ["style", "css", "sass"]
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      },
      {
        test   : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        loader : 'url-loader'
      },
      {
        test: /\.(png|jpg|gif)$/,
        loader: 'file-loader'
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  }
};

我正在尝试像这样用作内联 CSS 背景图像:

<div class="inner-panel"
     style="background-image: url("/common/img/split-image/image.jpg");">
</div>

它也不能用作内嵌图像:

<img src="/common/img/split-image/image.jpg">

【问题讨论】:

    标签: javascript html css webpack


    【解决方案1】:

    问题在于您的图像路径,而不是您的 webpack 配置。

    尝试像这样在路径的开头添加./

    "./common/img/split-image/image.jpg"
    

    除此之外,您还应该查看您的文件需要,并确保将它们放置在您想要放置它们的位置。

    由于您使用的是文件加载器(我认为 React 也是如此),因此您将如何使用它的示例如下:

    //CJS
    var file = require("file!./file.png");
    //ES6
    import file from "file!./file.png";
    
    //Later inside a React component
        const inStyle = {
            background-image: 'url(' + file + ')'
        }
        <div style={inStyle}/>
    

    (React 使用对象而不是字符串作为样式属性)

    url-loader 应该是一样的。希望这会有所帮助。

    【讨论】:

    • 谢谢,我认为文件根本没有被加载。如何配置文件要求?
    • 我将用有关文件加载器的更多信息修改我的评论。
    • 我必须删除文件!从导入到让它工作,但它现在工作。非常感谢您的帮助@DogPawHat
    猜你喜欢
    • 2018-01-06
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多