简体   繁体   English

如何使用Webpack和Sass进行spriting?

[英]How to use spriting with Webpack and Sass?

I am moving my build system from Grunt with custom tasks to Webpack. 我正在将我的构建系统从具有自定义任务的Grunt移动到Webpack。 As for JavaScript modules it works great, but I'm not so sure what to do with my Sass stylesheets. 至于JavaScript模块,它工作得很好,但我不太确定如何使用我的Sass样式表。

I have dependencies on Sass files in my AMD modules, which Webpack can read and generate bundle.css from. 我依赖于我的AMD模块中的Sass文件,Webpack可以从中读取并生成bundle.css。 But I would ideally like to have my build pipeline generate sprites using spritesmith, then copy the images to the build dir and use the Sass mixins to generate correct CSS rules. 但我最好让我的构建管道使用spritesmith生成精灵,然后将图像复制到构建目录并使用Sass mixins生成正确的CSS规则。

I have researched this a lot both on SO and Google, but haven't found anyone doing similar scenario. 我在SO和谷歌上都研究了很多,但没有找到任何人做类似的情况。 Should I use solely webpack? 我应该只使用网络包吗? Or should I maybe have separate Grunt task watching the images, generating sprites and then run Webpack over that? 或者我应该有单独的Grunt任务观看图像,生成精灵,然后运行Webpack?

I have a similar problem, I have a directory full of png files that I need to convert to CSS so that a div with the correct class name will load the image. 我有一个类似的问题,我有一个目录充满了我需要转换为CSS的png文件,以便具有正确类名的div将加载图像。 I would like to use url-loader so that small files are inlined. 我想使用url-loader以便内联小文件。

The problem is of course that you can't specify a directory as something a loader should load, only existing files. 问题当然是您无法将目录指定为加载程序应加载的内容,而只能指定现有文件。

My solution is to create a custom loader in the png dir and give it itself as input, so it can glob the files in its own dir and export the CSS with all the require statements for the png files. 我的解决方案是在png目录中创建一个自定义加载器并将其自身作为输入,因此它可以在自己的目录中对文件进行全局处理,并使用png文件的所有require语句导出CSS。

This is the webpack entry for it: 这是它的webpack条目:

'!!style!css!./resources/images/images-as-css-loader.coffee!./resources/images/images-as-css-loader'

The loader code (coffeescript but you get the idea): 加载器代码(coffeescript,但你明白了):

glob = require 'glob'
path = require 'path'
sizeOf = require 'image-size'

module.exports = (dummy) ->
  this.cacheable true

  dir = path.dirname this.resourcePath
  entries = for file in glob.sync "#{dir}/*.png"
    @addDependency file
    className = (path.basename file, '.png')
    imgDim = sizeOf file
    """
      .#{className} {
        width: #{imgDim.width}px;
        height: #{imgDim.height}px;
        background-repeat: no-repeat;
        background-image: url('~!!url?limit=1024!#{file}');
      }

    """

  # Return CSS text
  return entries.join ''

You can then use the webpack text extract plugin to move the CSS to a file, which I do for the production build. 然后,您可以使用webpack文本提取插件将CSS移动到一个文件,我为生成版本执行此操作。 For dev I just let the style loader inject it. 对于dev我只是让样式加载器注入它。

我有类似的问题,我能够想出的唯一解决方案是编写自己的插件

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

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