zoukankan      html  css  js  c++  java
  • Webpack 多页面打包提取公共库和公共方法

    前端页面基础资源

    有些页面使用的基础库是一样的,并且也有公共的模块
    对于这些资源如果打包的时候每个都打一份,会导致打包的体积比较大

    webpack提取页面公共资源,比如公共包,公共模块?

    webpack 提取页面公共资源

    基础库分离

    思路: 将react、react-dom通过cdn引入,不打入bundle中
    方法: 1. 使用html-webpack-externals-plugin 2. 使用splitChunks

    splitChunks

    webpakc4内置的,替代commonChunkPlugin插件(webpack3常用),功能非常强大,做代码分割基本上离不开这个库

    chunks参数说明
    async:异步引入的库进行分离(默认,只分析异步、动态引入的库)
    initial: 同步引入的库进行分离(同步的就分离)
    all: 所有引入的库进行分离(推荐,不论同步、异步都提取)

    默认参数

    module.exports = {
        optimizatin:{
            splitChunks:{
                chunks:'async', // 需要分离哪些库
                minSize:30000, // 抽离公共包最小的大小,30k
                maxSize:0, // 最大的大小,单位是字节
                minChunks:1, // 最小引用的次数,比如一个方法在多个页面都使用到
                maxAsyncRequests:5, // 浏览器每次请求异步资源的次数.通过插件分离出的库被同时请求的数量
                maxInitialRequests:3, 
                automaticNameDelimiter:'~',
                name:true,
                cacheGroups:{
                    vendors:{
                        test:/[\/]node_modules[\/]/, // 匹配出要分离的包
                        priority:-10
                    }
                }
            }
        }
    }
    

    提取公共包 HtmlWebpackExternalsPlugin方式

    安装

    npm i html-webpack-externals-plugin@3.8.0 -D
    

    配置HtmlWebpackExternalsPlugin

    module.exports = {
        plugins:[
            new HtmlWebpackExternalsPlugin({
                {
                    module:'react',
                    entry:'https://now8.gtimg.com/now/lib/16.8.6/react.min.js',
                    global:'React'
                },
                {
                    module:'react-dom',
                    entry:'https://now8.gtimg.com/now/lib/16.8.6/react-dom.min.js',
                    global:'ReactDom'
                }
            })
        ]
    }
    

    最后在index.html模板页面引入cdn脚本

    splitChunks方式

    对于多页面应用,如果不提取公共库,那么每个页面都会把公共包打包进去,造成bunlde体积冗余
    可以使用splitChunks将公共库提取出来, 需要的页面都使用同一个包

    1. 分离公共库配置
    module.exports = {
        optimization:{
            splitChunks:{
                cacheGroups:{
                    commons:{
                        test:/(react)|(react-dom)/,  // 匹配
                        name:'vendors', // 将react和react-dom提取出来叫vendors
                        chunks:'all'
                    }
                }
            }
    
        }
    }
    

    分离之前

    可以看到comp1 和 comp 因为都将react打包引入了,导致两个包都有100多K
                    Asset        Size   Chunks             Chunk Names
                 comp.html    2.88 KiB          [emitted]  
                comp1.html    2.89 KiB          [emitted]  
        comp1_2174f810.css   126 bytes       1  [emitted]  comp1
         comp1_80beb5fc.js     119 KiB       1  [emitted]  comp1
         comp_2174f810.css   126 bytes       0  [emitted]  comp
          comp_a0497db7.js     119 KiB       0  [emitted]  comp
        dalao_982163fc.jpg    35.8 KiB          [emitted]  
           helloworld.html   298 bytes          [emitted]  
    helloworld_06fed627.js  1000 bytes       2  [emitted]  helloworld
    

    分离之后
    此时react/react-dom已经被提取成vendors,comp和comp1仅有9.45kb,大大优化了打包体积

                     Asset        Size  Chunks             Chunk Names
                 comp.html    2.95 KiB          [emitted]  
                comp1.html    2.95 KiB          [emitted]  
         comp1_e1399198.js    9.45 KiB       2  [emitted]  comp1
          comp_f76b4f2b.js    9.45 KiB       1  [emitted]  comp
        dalao_982163fc.jpg    35.8 KiB          [emitted]  
           helloworld.html   415 bytes          [emitted]  
    helloworld_149cdeea.js  1000 bytes       3  [emitted]  helloworld
      vendors_6d383d43.css   126 bytes       0  [emitted]  vendors
       vendors_898437c4.js     110 KiB       0  [emitted]  vendors
    

    要使用vendors的话需要在HtmlWebackPlugin中chunks加入'vendors'

    {
        chunks:['vendors',pageName]
    }
    
    1. 提取公共方法配置

    分别minSize设置0和1000k大小
    minchunks为三次

    同时修改HtmlWebpackPlugin的chunks属性

    module.exports = {
        optimization: {
            splitChunks: {
                minSize:0,  // 最小为0kb
                cacheGroups: {
                    commons: {
                        name: 'commons', // 对应htmlwebpackplugin中添加的chunk name 
                        chunks: 'all', 
                        minChunks: 2,  // 最小引用次数
                    }
                }
            }
        }
    }
    

    完整配置

    'use strict';
    
    const path = require('path');
    const glob = require('glob')
    
    // 将css commonjs 抽成css文件
    const MiniCssExtractPlugin = require('mini-css-extract-plugin')
    // 压缩css文件
    const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
    // 压缩html,有几个入口就对应几个html
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    // 每次构建的时候自动清除之前的dist目录下的文件
    const CleanWebpackPlugin = require('clean-webpack-plugin')
    
    const setMPA = () => {
        const entry = {}
        const HtmlWebpackPlugins = []
        const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'))
        Object.keys(entryFiles).map(index => {
    
            const entryFile = entryFiles[index]
    
            const match = entryFile.match(/src/(.*)/index.js/)
            const pageName = match && match[1]
            entry[pageName] = `./src/${pageName}/index.js`
    
            HtmlWebpackPlugins.push(new HtmlWebpackPlugin({
                // html模板所在路径
                template: path.join(__dirname, `src/${pageName}/index.html`),
                // 指定输出文件名称
                filename: `${pageName}.html`,
                // 使用哪个chunk生成html页面
                chunks: ['commons', pageName],
                // 为true时,jscss会自动注入此html中来
                inject: true,
                // 处理换行,空格,注释
                minify: {
                    html5: true,
                    collapseWhitespace: true,
                    preserveLineBreaks: false,
                    minifyCSS: true,
                    minifyJS: true,
                    removeComments: false
                }
            }))
        })
    
        return {
            entry,
            HtmlWebpackPlugins
        }
    }
    
    const { entry, HtmlWebpackPlugins } = setMPA()
    
    module.exports = {
        // 生产模式还是开发模式
        mode: 'production',
        // 入口 指定入口文件
        entry,
        // 出口 
        output: {
            // 指定输出目录
            path: path.join(__dirname, 'dist'),
            filename: '[name]_[chunkhash:8].js'
        },
        // 配置loader
        module: {
            rules: [
                {
                    test: /.js$/,
                    use: 'babel-loader'
                },
                {
                    test: /.css$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        // 'style-loader', // 再将样式插入到style标签中
                        'css-loader' // 将css转换成commonjs
                    ]
                },
                {
                    test: /.less$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        // 'style-loader', // 再将样式插入到style标签中
                        'css-loader', // 将css转换成commonjs
                        'less-loader', // 将less文件转换成css文件
                        // 自动补齐css3前缀
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: () => [
                                    require('autoprefixer')(
                                        { browsers: ['last 2 version', '>1%', 'ios 7'] }
                                    )
                                ]
                            }
                        },
                        // px2rem-loader 移动端适配
                        {
                            loader: 'px2rem-loader',
                            options: {
                                remUnit: 75, // 1rem对应75px,10rem对应750px,适合750px视觉稿
                                remPrecision: 8 // px转rem后,小数点的位数
                            }
                        }
                    ]
                },
                {
                    test: /.(png|jpg|gif|jpeg)$/,
                    use: [
                        {
                            loader: 'file-loader',
                            // 图片指纹
                            options: {
                                name: '[name]_[hash:8].[ext]'
                            }
                            // loader: 'url-loader',
                            // options: {
                            //     limit: 40 * 1024 // 40k
                            // }
                        }
                    ]
                },
                {
                    test: /.(woff|woff2|eot|ttf|otf|otf)$/,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: '[name]_[hash:8].[ext]'
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            // css使用contenthash,避免css没变js变化的时候,css的hash值页随着发布一起变化
            new MiniCssExtractPlugin({
                filename: '[name]_[contenthash:8].css',
            }),
            // 压缩css文件
            new OptimizeCssAssetsPlugin({
                assetNameRegExp: /.css$/g,
                // css预处理器
                cssProcessor: require('cssnano')
            }),
            // 自动清除dist目录下的文件
            new CleanWebpackPlugin()
        ].concat(HtmlWebpackPlugins),  // 压缩html
        optimization: {
            splitChunks: {
                minSize: 0, 
                cacheGroups: {
                    commons: {
                        name: 'commons',
                        chunks: 'all',
                        minChunks: 2,
                    }
                }
            }
        }
    }
    

    json

    {
      "name": "02beginning",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "build": " webpack --config webpack.prod.js",
        "watch": "webpack --watch",
        "dev": "webpack-dev-server --config webpack.dev.js --open"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "@babel/core": "^7.4.4",
        "@babel/preset-env": "^7.4.4",
        "@babel/preset-react": "^7.0.0",
        "autoprefixer": "^9.5.1",
        "babel-loader": "^8.0.5",
        "css-loader": "^2.1.1",
        "cssnano": "^4.1.10",
        "file-loader": "^3.0.1",
        "glob": "^7.1.4",
        "html-webpack-plugin": "^3.2.0",
        "less": "^3.9.0",
        "less-loader": "^5.0.0",
        "mini-css-extract-plugin": "^0.6.0",
        "optimize-css-assets-webpack-plugin": "^5.0.1",
        "postcss-loader": "^3.0.0",
        "px2rem-loader": "^0.1.9",
        "raw-loader": "^0.5.1",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "style-loader": "^0.23.1",
        "url-loader": "^1.1.2",
        "webpack": "^4.31.0",
        "webpack-cli": "^3.3.2",
        "webpack-dev-server": "^3.3.1"
      },
      "dependencies": {
        "lib-flexible": "^0.3.2"
      }
    }
    
  • 相关阅读:
    SpringBoot-配置Druid-yml方式
    CentOS7下配置Nginx并实现简单的负载均衡
    用私有构造器或者枚举类型强化Singleton
    virtualenv虚拟环境的使用
    Windows平台安装Python
    window平台基于influxdb + grafana + jmeter 搭建性能测试实时监控平台
    easy-mock本地部署成功,访问报错:EADDRNOTAVAIL 0.0.0.0:7300 解决方案
    npm install 报错: WARN checkPermissions Missing write access to 解决方案
    npm install 报错:ERR! code EINTEGRITY 解决方案
    最新版chrome浏览器如何离线安装crx插件?(转载)
  • 原文地址:https://www.cnblogs.com/ltfxy/p/15349716.html
Copyright © 2011-2022 走看看