04-webpack: plugins

/**
    plugin:
        1.完成loader不能完成的事情
        2.本质上是一个具有 apply 方法的 JavaScript 对象。apply 方法会被 webpack compiler 调用,并且在整个编译生命周期都可以访问 compiler 对象
        3.配置方式引入示例:
          plugins: [
            new webpack.ProgressPlugin(),
            new HtmlWebpackPlugin({ template: './src/index.html' }),
          ]
        4.Node API方式引入
            const webpack = require('webpack'); // 访问 webpack 运行时(runtime)
            const configuration = require('./webpack.config.js');

            let compiler = webpack(configuration);

            new webpack.ProgressPlugin().apply(compiler);

            compiler.run(function (err, stats) {
              // ...
            });
          node API 方式引入可以看出,webpack 本质是一个函数,函数调用时接收 配置的 config options, 返回一个编译对象 compiler。
          编译过程就是 compiler 对象中方法执行的过程
        
        5.常用plugin,以及作用,参考 https://www.cnblogs.com/susu2020/p/12517001.html
            1. webpack内置压缩代码插件: UglifyJsPlugin
                new UglifyJsPlugin({
                    parallel: 4,
                    uglifyOptions: {
                        output: {
                        comments: false,
                        beautify: false,
                        },
                        compress: {
                        warnings: false
                        },
                    },
                    cache: true,
                })
            2. webpack内置提高打包效率,将第三方库和业务代码分开打包:CommonsChunkPlugin
                new webpack.optimize.CommonsChunkPlugin({
                    name: 'vendor',
                    filename: "js/vendor.js",
                    children: true,
                    minChunks: Infinity,
                })
            3. webpack内置自动加载模块,代替require和import插件:ProvidePlugin。
                new webpack.ProvidePlugin({     //自动加载模块
                     '$': "jquery",
                     'jQuery': "jquery",
                     'window.jQuery': "jquery",
                     'window.$': 'jquery'
                })
                也可以配置全局方法
                new webpack.ProvidePlugin({
                    _deepCopy: [path.join(__dirname, 'src/tools/index.js'),'deepCopy'], // 深拷贝函数
                    _formatTime: 'dayjs',  // dayjs 插件
                })
            4. webpack内置生成html文件的插件:html-webpack-plugin 生成HTML文件,并且在body中使用script标签引入你所有webpack生成的 bundle.js
                new HtmlWebpackPlugin({
                    template: 'src/index.html',
                })
            5. extract-text-webpack-plugin:将css模块和js模块分开打包,换句话说把css代码从js文件中抽离出来,单独出一个模块。https://blog.csdn.net/weixin_41134409/article/details/88416356
                const ExtractTextPlugin = require("extract-text-webpack-plugin");  //记得先install该模块
                /** ExtractTextPlugin.extract 提取样式函数参数说明:
                    use:指需要什么样的loader去编译文件
                    fallback: 这里表示不提取的时候,使用什么样的配置来处理css
                    publicfile:用来覆盖项目路径,生成该css文件的文件路径
                **/
                module: {
                    rules: [
                        {
                            test: /\.vue$/,
                            loader: 'vue-loader',
                            options: {
                                loaders: {
                                    scss: ExtractTextPlugin.extract({ fallback: 'vue-style-loader', use: 'css-loader!sass-loader' })
                                    css: ExtractTextPlugin.extract({ fallback: 'vue-style-loader', use: 'css-loader' }),
                                }
                            }
                        },
                        {
                            test: /\.css$/,
                            use: ExtractTextPlugin.extract({    //css的提取
                                fallback: "style-loader",
                                use: "css-loader"
                            })
                        },
                        {
                            test: /\.scss$/,
                            use: ExtractTextPlugin.extract({   //css的提取
                                fallback: "style-loader",
                                use: ['sass-loader','postcss-loader']
                            })
                        }
                    ]
                },
                plugins: [
                    new ExtractTextPlugin({
                        filename: 'css/[name].[contenthash].css',
                        allChunks: true //当为false的时候,只会提取初始化的时候引入的css,当allChunks属性为true时,会把异步引入的css也提取出来
                    })
                ]
            6. compression-webpack-plugin:生产环境可采用gzip压缩JS和CSS
                new CompressionPlugin({    //打包文件为giz格式
                    filename: '[path].gz[query]', //目标资源名称。[file] 会被替换成原资源。[path] 会被替换成原资源路径,[query] 替换成原查询字符串
                    algorithm: 'gzip',//算法
                    test: new RegExp('\\.(js|css)$'),
                    threshold: 10240,//只处理比这个值大的资源。按字节计算
                    minRatio: 0.8//只有压缩率比这个值小的资源才会被处理
                })
            7. CleanWebpackPlugin:重构之前删除dist文件,除dist/img文件
                new CleanWebpackPlugin({  
                    cleanOnceBeforeBuildPatterns:['**/*', '!img', '!img/**']
                })
                

                
        
        
        6.自定义plugin
            const pluginName = 'ConsoleLogOnBuildWebpackPlugin';
            class ConsoleLogOnBuildWebpackPlugin {
              apply(compiler) {
                compiler.hooks.run.tap(pluginName, (compilation) => {
                  console.log('webpack 构建正在启动!');
                });
              }
            }
            module.exports = ConsoleLogOnBuildWebpackPlugin;



**/

 

posted @ 2022-08-08 16:03  monkey-K  阅读(20)  评论(0编辑  收藏  举报