webpack学习(七)打包压缩图片

使用插件webpack-spritesmith生成雪碧图

1、安装webpack-spritesmith;
npm install --save-dev webpack-spritesmith

2.配置webpack.config.js

        new SpritesmithPlugin({     //生成的雪碧图本身就压缩了图片大小
            src: {
                cwd: path.resolve(__dirname, 'src/image/icon'),  //准备合并成sprit的图片存放文件夹
                glob: '*.png'  //哪类图片
            },
            target: {
                image: path.resolve(__dirname, 'dist/sprites/sprites.png'),  // sprite图片保存路径
                css: path.resolve(__dirname, 'dist/sprites/_sprites.css')  // 生成的css保存在哪里
            },
            apiOptions: {
                cssImageRef: "../sprites/sprites.png" //css根据该指引找到sprite图
            }
        }),

贴一张目录

webpack学习(七)打包压缩图片_第1张图片

3、执行webpack打包指令,执行后打包生成dist/sprites/文件

4、index.html文件中引入sprite.css,如:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webpacktitle>
    <link href="bundle.3a78e3af7afe10200470.css" rel="stylesheet">head>
    <link href="sprites/_sprites.css" rel="stylesheet">  //引用就可以了
head>
<body>
    
    <div class="test">测试webpackdiv>
    <div class="test1">测试webpack1div>
    <div class="icon-a">adiv>  //需要的地方来用就可以了
    <div class="icon-b">bdiv>
<script type="text/javascript" src="bundle-3a78e3af7afe10200470.js">script>
body>
html>

 合成后的sprites.png

webpack学习(七)打包压缩图片_第2张图片

合成后的sprites.css

.icon-a {  //名称为icon+图片名
  background-image: url(../sprites/sprites.png);
  background-position: 0px 0px;
  width: 50px;
  height: 50px;
}
.icon-b {
  background-image: url(../sprites/sprites.png);
  background-position: -50px 0px;
  width: 50px;
  height: 50px;
}
.icon-c {
  background-image: url(../sprites/sprites.png);
  background-position: 0px -50px;
  width: 50px;
  height: 50px;
}

 5.适用的场景

webpack学习(七)打包压缩图片_第3张图片

 

 
  

转载于:https://www.cnblogs.com/chaixiaozhi/p/8620766.html

你可能感兴趣的:(webpack,javascript,ViewUI)