webpack雪碧图的实现

步骤一 安装webpack-spritesmith

npm install --save-dev webpack-spritesmith
复制代码

步骤二 在webpack.config.js添加代码

var path = require('path');
var SpritesmithPlugin = require('webpack-spritesmith');
module.exports = {
    // ...
    module: {
        rules: [
            {test: /\.styl$/, use: [
                'style-loader',
                'css-loader',
                'stylus-loader'
            ]},
            {test: /\.png$/, use: [
                'file-loader?name=i/[hash].[ext]'
            ]}
        ]
    },
    resolve: {
        modules: ["node_modules", "spritesmith-generated"]
    },
    plugins: [
        new SpritesmithPlugin({
            src: {
                cwd: path.resolve(__dirname, 'src/ico'),
                glob: '*.png'
            },
            target: {
                image: path.resolve(__dirname, 'src/spritesmith-generated/sprite.png'),
                css: path.resolve(__dirname, 'src/spritesmith-generated/sprite.styl')
            },
            apiOptions: {
                cssImageRef: "~sprite.png"
            }
        })
    ]
};
复制代码

步骤三 执行webpack打包命令,则将在对应的文件夹生成css和png

使用方式:

块状元素:

<div class="icon-home">div>
复制代码

行内块状元素:

.icon {
  display: inline-block;
}
复制代码
<i class="icon icon-home">i>
复制代码

转载于:https://juejin.im/post/5b99dc416fb9a05d1227f391

你可能感兴趣的:(webpack)