如何在 webpack 中加载 sass 样式表中使用的图像?

新手上路,请多包涵

我正在使用 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;
}

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

 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: './'
  }
};

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

原文由 WitVault 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 496
2 个回答

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

问题在这里

loader: 'url-loader?limit=10000'

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

原文由 WitVault 发布,翻译遵循 CC BY-SA 3.0 许可协议

当使用 webpack 加载您的 css 及其访问的资产时,您的 css 需要遵循您在 JavaScript 中使用的相同模块命名规则 importrequire 调用。

假设 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');

原文由 Brandon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题