打包图片资源

1,下载安装 loader 包:

  npm install --save-dev html-loader url-loader file-loader,

  url-loader 依赖于 file-loader

src / index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webpack</title>
</head>
<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
    <img src="./angular.jpg" alt="angular">
</body>
</html>

src / index.js

import './index.less'

src / index.less

#box1{
  width: 100px;
  height: 100px;
  background-image: url('./vue.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#box2{
  width: 100px;
  height:100px;
  background-image: url('./react.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#box3{
  width: 100px;
  height:100px;
  background-image: url('./angular.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

2,webpack.config.js 配置

const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports={
    entry:'./src/index.js',
    output:{
        filename:'bundle.js',
        path:resolve(__dirname,"build")
    },
    module:{
        rules:[
            {
                test:/\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']  // 要使用多个loader处理用use
            },
            {
                test:/\.(jpg|png|gif)$/, //处理图片资源
                loader:'url-loader', //使用一个loader直接写loader
                options:{
                    limit:8*1024,//图片小于8kb,就会被base64处理
                }
            },
            {
                test:/\.html$/, //处理html文件的img图片(负责引入img,从而能被url-loader进行处理)
                loader:'html-loader'
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html'
        })
    ],
    mode:'development'
}

base64处理图片:

优点:减少请求数量,减轻服务器压力(base64在客户端本地解码)

缺点:图片体积会更大,文件请求速度更慢(图片过大继续使用 base64会导致cpu调用率上升,网页加载变卡)

npx webpack 指令打包:

打包后的 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webpack</title>
</head>
<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
    <img src="830bf3c820562c180c8975c2a0d00557.jpg" alt="angular">
<script src="bundle.js"></script></body>
</html>

 另一张小于 8kb 的图片使用了 base64打包,加载页面时会直接加载进来,其他大于 8kb 的图片重新编译打包,

 此外,图片文件的哈希命名可以进行重命名,只保留10位哈希值:

 

posted @ 2020-06-04 20:34  shanlu  阅读(182)  评论(0编辑  收藏  举报