先執行installcss
cnpm install webpack-spritesmithwebpack
文件位置web
build\webpack.dev.conf.jsnpm
添加內容:api
const SpritesmithPlugin = require('webpack-spritesmith');
找到 less
文件內 plugins:flex
我是生成less文件後,單位rem實現雪碧圖的響應式適配,用的是阿里方案頁面內需引用flexbile.min.js(參考阿里手淘適配)ui
目錄結構:url
添加以下內容:spa
文件位置:
build\webpack.dev.conf.js
new SpritesmithPlugin({ // 目標小圖標 src: { cwd: path.resolve(__dirname, '../static/images/icon'), glob: '*.png' }, // 輸出雪碧圖文件及樣式文件 target: { image: path.resolve(__dirname, '../static/images/sprite.png'), css:[[path.resolve(__dirname, '../static/images/sprite.less'),{ format: 'function_based_template' }]] }, customTemplates: { 'function_based_template': path.resolve(__dirname, '../my_handlebars_template.handlebars') }, // 樣式文件中調用雪碧圖地址寫法 apiOptions: { cssImageRef: './sprite.png?v='+Date.parse(new Date()) }, spritesmithOptions: { algorithm: 'binary-tree' } })
添加文件:my_handlebars_template.handlebars
文件位置:項目根目錄下:\my_handlebars_template.handlebars
文件內容:
{{#block "sprites"}} {{#block "spritesheet"}} @img:url('{{{spritesheet.escaped_image}}}'); @r:75rem; .icon{ background-size: {{spritesheet.width}}/@r {{spritesheet.height}}/@r; background-repeat:no-repeat; display:inline-block; }; {{/block}} {{#each sprites}} .icon-{{{strings.name}}} { background-image: @img; background-position: {{offset_x}}/@r {{offset_y}}/@r; width: {{width}}/@r; height: {{height}}/@r }; {{/each}} {{/block}}
命令行內運行:
npm run dev 便可
生成這2個文件引用對應的less文件便可