webpack--插件配置:处理HTML中的图片(七)

目录结构

before

webpack--插件配置:处理HTML中的图片(七)

after

webpack--插件配置:处理HTML中的图片(七)

更改打包命令

package.json
就可以使用npm run build 代替webpack

"scripts": {
    "server": "webpack-dev-server",
    "build": "webpack"
  },

修改index.html

<div>
        <img src="./images/bb.png" alt="">
    </div>

html-withimg-loader

安装依赖

可以直接安装在dev环境

cnpm install html-withimg-loader --save-dev

修改url-loader

增加outputPath:'images/',

{
               test:/\.(png|jpg|gif)/ ,
               use:[{
                   loader:'url-loader',
                   options:{
                       limit:5000,
                       outputPath:'images/',
                   }
               }]
            }

配置html-withimg-loader loader

{
    test: /\.(htm|html)$/i,
     use:[ 'html-withimg-loader'] 
}

全部代码

const path = require('path');
const uglify = require('uglifyjs-webpack-plugin');
const htmlPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var website ={
    publicPath:"http://192.168.1.9:1717/"
}
module.exports = {
    // 入口 
    entry: {
        entry: './src/entry.js',
    },
    // 出口
    output: {
        //绝对路径
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        publicPath:website.publicPath
    },
    // 模块
    module: {
        //规则
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                  fallback: "style-loader",
                  use: "css-loader"
                })
              },
            {
                test: /\.(png|jpg|gif)/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 5000,
                        outputPath:'images/',
                    }
                }]
            },{
                test: /\.(htm|html)$/i,
                 use:[ 'html-withimg-loader'] 
            }
        ]
    },
    //插件
    plugins: [
        // new uglify()
        new htmlPlugin({
            minify: {
                removeAttributeQuotes: true
            },
            hash: true,
            template: './src/index.html'
        }),
        new ExtractTextPlugin("css/index.css"),
    ],
    //开发服务
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        host: '192.168.1.9',
        compress: true, //服务端是否启用压缩
        port: 1717
    }
}

运行阅览

npm run build
npm run server

webpack--插件配置:处理HTML中的图片(七)

相关推荐