I don’t know if you still use Sprite pictures of this kind of thing ~ heard that out of date? Ha, ha, ha, ha, ha. Anyway, I’m going to write it down.

Since I recently used it, I learned to use Webpack-Spritesmith to automatically generate Sprite images.

demand

There are many ICONS in the project, or similar buttons, etc., which cannot be replaced by iconFONT or SVG, so they can only be introduced after cutting images from the design draft.

However, the introduction of each icon individually will increase the number of HTTP requests when loading images, which may cause problems such as slow loading.

Therefore, I decided to use Sprite.

Automatically generate Sprite images

  1. The installation
npm i webpack-spritesmith
Copy the code
  1. Introduction to use
/ / webpack file

/* * Webpack-spritesmith **/
const fs = require('fs');
const SpritesmithPlugin = require('webpack-spritesmith');

/* * Custom spritesmith rule - spritesmith default unit is px, but I need to use REM, so custom rule, change the unit to REM **/
var templateFunction = function (data) {
  var getRem = function(val) {
    // Change $rem in _px2rem. SCSS
    const base = 75;
    return parseInt(val)/base + 'rem'
  }

// The format of the sprites. SCSS file generated
  var perSprite = data.sprites.map(function (sprite) {
    return `@mixin sprites-${sprite.name} {
      background-image: url(${data.sprites[0].image});
      background-size: ${getRem(data.spritesheet.width)} ${getRem(data.spritesheet.height)};
      width: ${getRem(sprite.width)};
      height: ${getRem(sprite.height)}; 
      background-position: ${getRem(sprite.offset_x)} ${getRem(sprite.offset_y)}; } `
  }).join('\n');
  return perSprite;
}

/* * New SpritesmithPlugin(); /* new SpritesmithPlugin(); But for convenience, the traversal is done here to achieve one-time configuration, so that each time only need to add the image file, it can be generated automatically, no need to do other configuration. * * /
const spritesmithTasks = []
const spritesImg = {}
const spritesScss = []

// SRC /assets/sprites / SRC /assets/sprites/${dirname
fs.readdirSync('./src/assets/sprites').map(dirname= > {
    if (fs.statSync(`./src/assets/sprites/${dirname}`).isDirectory()) {
        spritesmithTasks.push(
            new SpritesmithPlugin({
                src: {
                	// The folder where Sprite images need to be generated
                    cwd: path.resolve(__dirname, `.. /src/assets/sprites/${dirname}`), 
                    glob: '*.png'
                },
                target: {
                	// Sprite map generated image path
                    image: path.resolve(__dirname, `.. /src/assets/sprites/${dirname}.png`), 
                    css: [
                    	// Corresponding CSS file after Sprite image is generated
                      [path.resolve(__dirname, `.. /src/assets/sprites/_${dirname}.scss`), {
                        // Reference your own template
                        format: 'function_based_template'}}]].// Customize the CSS processing template
                customTemplates: {
                  'function_based_template': templateFunction,
                },
                // Call Sprite address writing in the style file
                apiOptions: {
                    cssImageRef: ` ~${dirname}.sprites.png`
                },
                spritesmithOptions: {
                    algorithm: 'binary-tree'.padding: 10 // The spacing of each Sprite icon}})),// Set the generated Sprite map path alias corresponding to the apioptions.cssimageref in the previous new SpritesmithPlugin
        spritesImg[` ~${dirname}.sprites.png`] = path.resolve(
          __dirname,
          `.. /src/assets/sprites/${dirname}.png`,),// The generated _${dirname}. SCSS file is also known as spritesScss file.
        spritesScss.push(
          `./src/assets/sprites/_${dirname}.scss`)}})constbaseResolve = { ... spritesImg,// Set the generated Sprite map path alias
  The '@': path.resolve(__dirname, './src'),};module.exports = {
  resolve: {
    alias: {
      ...baseResolve,
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',}},module: {
    rules: [{test: /\.scss$/,
            exclude: [/node_modules/].use: [
              require.resolve('style-loader'),
              {
                loader: 'sass-resources-loader'.options: {
                  resources: [
                    ...spritesScss, // Globally import the generated _${dirname}.scss]},},},],},plugins: [
    ...spritesmithTasks // New SpritesmithPlugin()]};Copy the code

For ease of understanding, the rest of the WebPack configuration was removed above, leaving only the configuration information about spritesmith.

After the configuration is complete, add the image that you want to generate the Sprite image to the corresponding folder. / SRC /assets/sprites/${dirname} if I need to generate a Sprite image of a button, create a button directory in/SRC /assets/sprites and import all the images into it.

Run the project!

PNG and _button.scss have been added to/SRC /assets/sprites.

Button.png is the resulting Sprite image

_button.scss is the CSS for each icon in the Sprite image, as shown below

@mixin sprites-btn_get_lottery_hover {
      background-image: url(~button.sprites.png);
      background-size: 11.88 rem 11.626666666666667 rem;
      width: 3.8133333333333335 rem;
      height: 1.36 rem; 
      background-position: -3.9466666666666668 rem -6.64 rem;
    }
@mixin sprites-btn_get_lottery {
      background-image: url(~button.sprites.png);
      background-size: 11.88 rem 11.626666666666667 rem;
      width: 3.8133333333333335 rem;
      height: 1.36 rem; 
      background-position: 0rem -6.64 rem;
    }
Copy the code

At this point, you only need to import ICONS in other CSS

.test {
	@include sprites-btn_get_lottery
}
Copy the code

knowledge

What are the benefits of using Sprite? What is the use of referring to Sprite

  • Reduce the number of page requests when loading images
  • Improve page loading speed
  • Reduce mouse hover bug: IE6 will not actively preload the mouse slide, i.e. a:hover background image, so if you use multiple images, the mouse slide will appear white phenomenon. With CSS Sprite, this doesn’t happen because only one image is needed. (Never met so I don’t understand ~)

confusion

  • What are the disadvantages of using Sprite in PC or mobile?

Thank you

As a rookie, basically rely on Baidu, ha ha ha, the following is the reference article, thank you ~

  • Custom Sprites CSS rule reference Using Webpack-Spritesmith to generate Sprite images

  • The traversal is also a reference, but I can’t find that page again, 😭, back to fill it ~

The above, only as the notes of CAI Nuo Nuo.