12

我正在使用Webpack捆绑我的模块,并在基于反应的应用程序中使用sass进行样式设置。

使用单独的样式表,我正在设置组件的背景图像并将该样式表加载到index.js. 样式表中的所有样式都应用于该组件,除了背景图像

这是我的示例样式表

$bg-img: url('/img/bg.jpg');

.show {
    position: relative;
    background: $black $bg-img center center;
    width: 100%;
    height: 100%;
    background-size: cover;
    overflow: hidden;
}

解决该问题的一种方法是明确要求图像,然后为反应组件创建内联样式。

img1 = document.createElement("img");
img1.src = require("./image.png");

但是我想在我的样式表加载后立即从我的图像文件夹中加载所有图像,而不是单独要求每个图像。

我的 webpack 配置文件是

module.exports = {
  devtool: 'source-map',
  entry: {
    main: [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server',
      './src/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/public/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
   loaders: [
      {
        test: /\.jsx?$/,
        include: path.join(__dirname, 'src'),
        loader: 'react-hot!babel'
      },
      {
        test: /\.scss$/,
        include: path.join(__dirname, 'sass'),
        loaders: ["style", "css?sourceMap", "sass?sourceMap"]
      },
      { 
        test: /\.(png|jpg)$/,
        include: path.join(__dirname, 'img'),
        loader: 'url-loader?limit=10000' 
     } // inline base64 URLs for <=10k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

我可能遗漏了一些琐碎的要点。任何帮助表示赞赏。

4

3 回答 3

22

啊……经过长时间的调试,我终于找到了问题所在。正是我的愚蠢使我挣扎。我想删除这个问题,但认为当遇到类似问题时它会帮助像我这样的新人。

问题就在这里

loader: 'url-loader?limit=10000'

我将文件大小限制设置为10kb,但并不真正知道它的作用。我正在加载的图像大小为21kb!当您复制其他一些 webpack 配置文件时会发生这种情况 :) javascript 疲劳的迹象!

于 2016-02-10T22:43:59.413 回答
5

当使用 webpack 加载你的 css 和它们访问的资产时,你的 css 需要遵循你在 JavaScriptimportrequire调用中使用的相同模块命名规则。

假设该img文件夹位于源代码树的根目录中,您应该在 scss 中像这样引用它:

// note there is no leading /, which tells "require()" to start from the root of your source tree
$bg-img: url('img/bg.jpg');

或者只是完全相对。假设你的源代码是这样的:

/src/styles.scss
/img/bg.jpg

styles.scss可以使用相对路径:

// note the path is relative to where the style.scss is in your source tree.
$bg-img: url('../img/bg.jpg');
于 2016-02-10T21:27:36.493 回答
0

我有类似的问题,但图像带有“.jpeg”扩展名。出于某种原因,将扩展名更改为“.jpg”对我有所帮助。

于 2017-08-17T09:22:45.133 回答