webpack 插件应用

plugin

1. clean-webpack-plugin

  • 介绍

主要用来清除文件,默认webpack打包后dist文件下的js文件是不会自动清除的,修改之后再次打包旧的文件会仍然存在

  • 安装
npm install --save-dev clean-webpack-plugin 
  • 引用
//webpack.config.js中添加CleanWebpackPlugin插件
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
    plugins: [
     new CleanWebpackPlugin(
            ['dist/main.*.js','dist/manifest.*.js',],  //匹配删除的文件
            ['dist']//删除整个dist

        )
     ]
}

2. html-webpack-plugin

  • 介绍
|- /dist //用于放打包后文件的文件夹
 |- bundle.js //出口文件
 |- index.html //模板文件
|- /node_modules
|- /src //用于放源文件的文件夹
 |- index.js //入口文件
|- package.json
|- webpack.config.js //webpack配置文件

如果在只有index.js一个入口文件,只需要在index.html直接手动引用出口文件

<script src="bundle.js"></script> <!--这是手动引用的bundle.js-->

如果多个入口文件就需要手动添加不同的出口文件会很麻烦。而html-webpack-plugin插件可以使用模板生成html,整个文件会自动引用出口文件。

  • index.js
import _ from 'lodash';
import printMe from './print.js';

function () {
}
  • webapck.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        app: './src/index.js', //多个入口文件
        print: './src/print.js'
    },
    plugins: [ //webpack 通过 plugins 实现各种功能, 比如 html-webpack-plugin 使用模版生成 html 文件
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: 'Test Index ',
            template: './src/index.html',
            filename: 'index.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
             chunks: ['index'],//生成的html就只会载入自身需要的bundle.js
        })new HtmlWebpackPlugin({
            title: 'Test Print',
            template: './src/index.html',
            filename: 'print.html', //设置生成的HTML文件的名称, 支持指定子目录,如:assets/admin.html
            chunks: ['print']//生成的html就只会载入自身需要的bundle.js
        })
    ],
    output: {
        filename: '[name].bundle.js', //根据入口文件输出不同出口文件
        path: path.resolve(__dirname, 'dist')
    }
};
  • 打包后的index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
  <script type="text/javascript" src="app.bundle.js"></script>
  <script type="text/javascript" src="print.bundle.js"></script></body>
</html>
  • 提取公共模块
    在index.js 和 print.js中引入公共模块,比如 公共样式、封装的api
    可以将这些公共的模块提取出来,在webpack.config.js中的optimization添加一个splitChunks进行配置。
 optimization: {
    splitChunks: {
      // 自动提取所有公共模块到单独 bundle
      chunks: 'all'
    }
  },

打包后就会生成一个入口公共的模块index~print.bundle.js

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不叫猫先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值