简体   繁体   English

无法使用sass-loader(Webpack)加载背景图像

[英]Failing to load background-image with sass-loader (Webpack)

I'm having trouble trying to get the browser to successfully find a background image whilst using webpack and sass-loader/style-loader/css-loader. 我在尝试使用webpack和sass-loader / style-loader / css-loader尝试使浏览器成功找到背景图像时遇到麻烦。

The path seems to be right, because whenever I change it the compile process fails, but as it is, it is ok. 路径似乎是正确的,因为每当我更改它时,编译过程都会失败,但是按原样,这是可以的。

So far I have... 到目前为止,我有...

Component 零件

import React from 'react'

const Image = () => (
   <div className='sprite-container sprite-1'>
   </div>
)

export default Image

CSS 的CSS

.sprite-container {
   width: 100px;
   height: 100px;
   border-radius: 100%;
   border: 1px solid blue; // I put this just to confirm the container div is there, which it is.
   background-image: url('/img/spritesheet.png');
   background-repeat: no-repeat;
   position: absolute;
   top: 250px;
   right: 20px;
}

.sprite-1 {
   background-position: -100px, -100px;
}

As it is, the div is transparent. 实际上,div是透明的。 The container is there but the background image fails to load. 容器在那里,但是背景图像无法加载。 I'm new to compiling SASS in Webpack, so maybe this is something to do with my file structure. 我是在Webpack中编译SASS的新手,所以也许这与我的文件结构有关。

This is the relevant part of my file tree: 这是我文件树的相关部分:

- src
   - static (all static assets are served from this folder)
      - img
         -- spritesheet.png
   - styles
         -- app.scss
   -- app-client.js (importing app.scss here)

I'm importing the app.scss into my main js file, app-client.js (which React mounts to the application). 我正在将app.scss导入我的主要js文件app-client.js (React会安装到应用程序中)。

Does the path given in the background-image css property need to be relative the root directory or the stylesheet? background-image css属性中给定的路径是否需要相对于根目录或样式表? I'm assuming the root directory ( /static ). 我假设是根目录( /static )。

Any help appreciated. 任何帮助表示赞赏。


UPDATE 更新

File tree 文件树

- src
   - static (all static assets are served from this folder)
      - img
         -- spritesheet.png
      - js
         -- bundle.js
   - styles
         -- app.scss
   -- app-client.js (importing app.scss here)

webpack.config.js webpack.config.js

const debug = process.env.NODE_ENV !== "production";

const webpack = require('webpack');
const path = require('path');

// const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  devtool: debug ? 'inline-sourcemap' : null,
  entry: path.join(__dirname, 'src', 'app-client.js'),
  devServer: {
    inline: true,
    port: 3333,
    contentBase: "src/static/",
    historyApiFallback: {
      index: '/index-static.html'
    }
  },
  output: {
    path: path.join(__dirname, 'src', 'static', 'js'),
    publicPath: "/js/",
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
         test: path.join(__dirname, 'src'),
         loader: ['babel-loader'],
         query: {
            cacheDirectory: 'babel_cache',
            presets: debug ? ['react', 'es2015', 'react-hmre'] : ['react', 'es2015']
         }
      },
      {
         test: /\.scss$/,
         loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
         // loader: ExtractTextPlugin.extract(
         //     'style', // The backup style loader
         //     'css?sourceMap!sass?sourceMap'
         // )
      },
      {
         test: /\.png$/,
         loader: "url-loader?limit=10000&minetype=image/jpg"
      }
    ]
  },
  plugins: debug ? [] : [
   //  new ExtractTextPlugin('styles.css'),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false },
      mangle: true,
      sourcemap: false,
      beautify: false,
      dead_code: true
    }),
  ]
};

package.json package.json

{
  "name": "***",
  "version": "1.0.0",
  "description": "***",
  "main": "src/server.js",
  "repository": "**REPO**",
  "scripts": {
    "start": "NODE_ENV=production node_modules/.bin/babel-node --presets 'react,es2015' src/server.js",
    "start-dev": "npm run start-dev-hmr",
    "start-dev-single-page": "node_modules/.bin/http-server src/static",
    "start-dev-hmr": "node_modules/.bin/webpack-dev-server --progress --inline --hot",
    "build": "NODE_ENV=production node_modules/.bin/webpack -p"
  },
  "author": "***",
  "license": "UNLICENSED",
  "dependencies": {
    "axios": "^0.15.3",
    "babel-cli": "^6.11.4",
    "babel-core": "^6.13.2",
    "babel-loader": "^6.2.5",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-object-rest-spread": "^6.22.0",
    "babel-preset-es2015": "^6.13.2",
    "babel-preset-react": "^6.11.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-stage-2": "^6.22.0",
    "ejs": "^2.5.1",
    "express": "^4.14.0",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "react-redux": "^5.0.2",
    "react-router": "^2.6.1",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.4",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "css-loader": "^0.26.1",
    "file-loader": "^0.9.0",
    "http-server": "^0.9.0",
    "node-sass": "^4.3.0",
    "react-hot-loader": "^1.3.0",
    "sass-loader": "^4.1.1",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.14.1"
  }
}

I ran into the same problem. 我遇到了同样的问题。 I found that you can include ?url=false in your css-loader to disable url handling. 我发现您可以在CSS加载程序中包含?url=false来禁用url处理。 Then you can just place an image in your public folder for css to access. 然后,您可以将图像放在公共文件夹中以供CSS访问。 The image won't be run through webpack, but it will get you past webpack's compile errors and still allow images to be accessed. 该映像不会通过webpack运行,但是它将使您摆脱webpack的编译错误,并仍然允许访问映像。

So here is my new object in the module.loaders array: 所以这是我在module.loaders数组中的新对象:

{
    test: /\.s?css$/,
    use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader?url=false', 'sass-loader']
    })
}

Ok, I found the answer on another stack overflow question: Webpack - background images not loading 好的,我在另一个堆栈溢出问题上找到了答案: Webpack-无法加载背景图片

It turns out it was a bug, caused by the sourceMap of css-loader . 事实证明这是一个错误,由css-loader的sourceMap引起。

I changed this... 我改变了这个...

{
   test: /\.scss$/,
   loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
}

...to this: ...对此:

{
   test: /\.scss$/,
   loaders: [ 'style', 'css', 'sass?sourceMap' ]
}

Hope that helps anyone else who faces this problem as it wasted a good few hours for me! 希望对其他遇到此问题的人有所帮助,因为这对我来说浪费了好几个小时!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM