webpack学习笔记---性能优化篇

提高webpack的打包速度

  1. 尽可能在更少的文件中使用loader,比如在使用babel-loader时,通过exclude来排除掉在node_modules里面的js文件,这样可以提高打包速度。

  2. Plugin尽可能精简并且确保可靠(尽可能少的去使用插件)

  3. resolve参数要合理配置

  4. 使用DLLPlugin提高打包速度。核心思想时利用DLLPlugin和DLLReferencePlugin预编译资源模块,通过DLLPlugin来引进那些我们引用但是绝对不会改变的npm包来进行预编译,再通过DLLReferencePlugin将预编译的模块加载进来。

    1. 新建一个文件,名字叫做webpack.dll.js,里面内容如下:
    const path = require('path');
    const webpack = require('webpack');
    
    module.exports={
        mode:'production',
        entry:{
            vendors:['vue','vue-router']//这里写的是不会修改的那些只用解析一次的模块
        },
        output:{
            filename:"[name].dll.js",//打包生成的文件名字,这里最终生成的文件是vendors.dll.js
            path:path.resolve(__dirname,"./dll"),//这些文件打包之后会存在dll文件夹里
            library:'[name]'//将打包出来的东西暴露给全局
        },
        plugins:[
            new webpack.DLLPlugin({
                name:'[name]',//这里和output属性的libiary保持一致
                path:path.resolve(__dirname,'./dll/[name].manifest.json')
            })
        ]
    }
    
    
    1. 在package.json的script中加上一条指令:
    "script":{
        "build:dll":"webpack --config webpack.dll.js"
    }
    
    1. 在命令行里运行npm run build:dll
    2. 安装另外一个插件npm install add-asset-html-webpack-plugin -D
    3. 修改webpack.common.js文件,在里面新增如下内容:
    const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');
    plugins:[
        //这个插件的作用是往htmlwebpackplugin插件生成的html上面新增一些静态文件,这里新增的是vendors.dll.js
        new AddAssetHtmlWebpackPlugin({
            filepath:path.resolve(__dirname,'vendors.dll.js')
        }),
        new webpack.DLLReferencePlugin({
            manifest:path.resolve(__dirname,'./dll/vendors.manifest.json')
        })
    ]
    
    1. 使用parallel-webpack,happypack多进程打包

    多页面应用打包

    // 多入口
    let path = require('path')
    let HtmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
        mode: 'development',
        entry: {
            home: './src/index.js',
            other: './src/other.js'
        },
        output: {
            filename: "[name].js",//这里的name就是entry里面的两个文件,可以是home,也可以是other
            path: path.resolve(__dirname, 'dist2')
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: './index.html',
                filename: 'home.html',
                //在chunks里面加入你想在这个页面中引入的js文件。
                chunks: ['home']//表示home.html里面引入的是打包生成的home.js
            }),
            new HtmlWebpackPlugin({
                template: './index.html',
                filename: 'other.html',
                chunks: ['other', 'home']   // other.html 里面有 other.js & home.js
            }),
        ]
    }
    
    

 上一篇
与位置相关的API辨析 与位置相关的API辨析
与位置相关的API辨析screen系列: screenLeft:浏览器左边距离屏幕的的距离 sceenTop:浏览器页面顶部距离屏幕上边的距离 inner系列 innerHeight:视口高度 innerWidth:视口宽度 offse
2019-09-02
下一篇 
webpack学习---基础配置篇 webpack学习---基础配置篇
webpack:模块打包机 webpack安装:推荐在项目内本地安装,不推荐使用全局安装。 如果配置文件的名字不是webpack.config.js的话,在使用npx webpack进行打包的时候要npx webpack --config
  目录