使用插件webpack-spritesmith生成雪碧圖javascript
一、安裝webpack-spritesmith;
css
npm install --save-dev webpack-spritesmith
2.配置webpack.config.jshtml
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圖 } }),
貼一張目錄java
三、執行webpack打包指令,執行後打包生成dist/sprites/文件webpack
四、index.html文件中引入sprite.css,如:web
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webpack</title> <link href="bundle.3a78e3af7afe10200470.css" rel="stylesheet"></head> <link href="sprites/_sprites.css" rel="stylesheet"> //引用就能夠了 </head> <body> <!--測試webpack--> <div class="test">測試webpack</div> <div class="test1">測試webpack1</div> <div class="icon-a">a</div> //須要的地方來用就能夠了 <div class="icon-b">b</div> <script type="text/javascript" src="bundle-3a78e3af7afe10200470.js"></script> </body> </html>
合成後的sprites.pngnpm
合成後的sprites.cssapi
.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.適用的場景測試