webpack4 - 5.图片处理

前端项目中除了html、css、js,不可避免地要处理图片文件,webpack打包图片文件是通过file-loaderurl-loader处理的。

url-loader可以将指定大小及以下的图片文件转成base64写入js,避免额外请求图片资源,如果超过指定大小再使用file-loader打包图片文件。

接下来对上一篇的代码稍作修改,来演示webpack是如何打包图片的。

1.打包css中的图片

安装依赖

npm install --save-dev webpack \
webpack-cli \
style-loader \
css-loader \
file-loader \
url-loader \
html-webpack-plugin \
mini-css-extract-plugin

package.json

  "devDependencies": {
    "css-loader": "^1.0.0",
    "file-loader": "^2.0.0",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.4.2",
    "style-loader": "^0.23.0",
    "url-loader": "^1.1.1",
    "webpack": "^4.19.0",
    "webpack-cli": "^3.1.0"
  }

项目代码结构如下

.
├── package-lock.json
├── package.json
├── src
│   ├── css
│   │   └── index.css
│   ├── img
│   │   ├── bg.png
│   ├── js
│   │   └── index.js
│   └── page
│       └── index.html
└── webpack.config.js

src/page/index.html




    
    Title


src/js/index.js

import '../css/index.css'

src/css/index.css

body {
    color: red;
    background: green;
}

.bg {
    width: 400px;
    height: 400px;
    background-image: url(../img/bg.png);
}

web pack.config.js

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: {
        index: './src/js/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].[hash:8].js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'  // 特别重要,否则css文件打包后其中引用的图片文件不正确
                        }
                    },
                    "css-loader"
                ]
            },
            {
                test:/\.(png|jpg|gif|jpeg|svg)$/,
                use:[
                    {
                        loader: "url-loader",
                        options: {
                            name: "[name].[hash:5].[ext]",
                            limit: 1024, // size <= 1kib
                            outputPath: "img"
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "css/[name].[hash:8].css",
        }),
        new HtmlWebpackPlugin(
            {
                template: './src/page/index.html',
                filename:'./page/index.html',
                hash: false,
                chunks: ['index']
            }
        )
    ]
};

执行webpack命令打包

$ webpack
Hash: 0317ffd61e75e401e3d3
Version: webpack 4.19.0
Time: 550ms
Built at: 09/18/2018 0:16:01 AM
                 Asset       Size  Chunks             Chunk Names
      img/bg.c1387.png    246 KiB          [emitted]  
css/index.0317ffd6.css  142 bytes   index  [emitted]  index
  js/index.0317ffd6.js   4.49 KiB   index  [emitted]  index
     ./page/index.html  355 bytes          [emitted]  
Entrypoint index = css/index.0317ffd6.css js/index.0317ffd6.js
[./src/css/index.css] 39 bytes {index} [built]
[./src/js/index.js] 25 bytes {index} [built]
    + 1 hidden module
Child html-webpack-plugin for "page/index.html":
     1 asset
    Entrypoint undefined = ./page/index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/page/index.html] 436 bytes {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 519 bytes {0} [built]
        + 1 hidden module
Child mini-css-extract-plugin node_modules/css-loader/index.js!src/css/index.css:
               Asset     Size  Chunks             Chunk Names
    img/bg.c1387.png  246 KiB          [emitted]  
    Entrypoint mini-css-extract-plugin = *
    [./node_modules/css-loader/index.js!./src/css/index.css] ./node_modules/css-loader!./src/css/index.css 406 bytes {mini-css-extract-plugin} [built]
    [./src/img/bg.png] 62 bytes {mini-css-extract-plugin} [built]
        + 2 hidden modules

最终在dist目录下生成以下文件

.
├── css
│   └── index.0317ffd6.css
├── img
│   └── bg.c1387.png
├── js
│   └── index.0317ffd6.js
└── page
    └── index.html

2.打包html中的图片

需要补充说明的是file-loaderurl-loader不能处理html中的图片(如img的src属性引用的图片),如果要处理html中的图片,需要另外使用其它loader。

这里使用的是html-loader

npm install --save-dev html-loader

修改‵webpack.config.js‵配置,添加html-loader相关的处理,另外还要修改url-loader的options

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: {
        index: './src/js/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].[hash:8].js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '../'  // 特别重要,否则css文件打包后其中引用的图片文件不正确
                        }
                    },
                    "css-loader"
                ]
            },
            {
                test: /\.html$/,
                use: {
                    loader: 'html-loader'
                }
            },
            {
                test:/\.(png|jpg|gif|jpeg|svg)$/,
                use:[
                    {
                        loader: "url-loader",
                        options: {
                            name: "img/[name].[hash:5].[ext]",
                            limit: 1024, // size <= 1kib
                            // outputPath: "img",
                            publicPath: "../"
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "css/[name].[hash:8].css",
        }),
        new HtmlWebpackPlugin(
            {
                template: './src/page/index.html',
                filename:'./page/index.html',
                hash: false,
                chunks: ['index']
            }
        )
    ]
};

在原来的src/page/index.html中添加




    
    Title


执行webpack命令后,在dist目录下生成的文件如下

.
├── dist
│   ├── css
│   │   └── index.146e059b.css
│   ├── img
│   │   ├── bg.27ec7.png
│   │   └── test.09f8d.png
│   ├── js
│   │   └── index.146e059b.js
│   └── page
│       └── index.html

你可能感兴趣的:(webpack4 - 5.图片处理)