webpack5做了哪些更新?

450 阅读1分钟

清除输出目录

webpack5清除输出目录可用,无需安装clean-webpack-plugin,具体用法如下:

module.exports = {
    output:{
        clean:true
    }
}

top-level-await

webpack5现在允许在模块的顶级代码中直接使用await,具体用法如下:

// src/index.js
const resp = await fetch("http://www.baidu.com");
const jsonBody = await resp.json();
export default jsonBody;

目前top-leval-await还未成为正式标准。因此,对于webpack5而言,该功能是作为experiments发布的,需要在webpack.config.js中配置开启

module.exports = {
    experiments:{
        topLevelAwait:true
    }
}

打包体积优化

webpack5对模块的合并、作用域提升、tree shaking等处理更加智能

打包缓存开箱即用

在webpack4中,需要使用cache-loader缓存打包结果,以优化之后的打包性能。 在webpack5中,默认就已经开启了打包缓存,无需再安装cache-loader。 默认情况下,webpack5中是将模块的打包结果缓存到内存中,可以通过cache配置进行更改

const path = require("path");
module.exports = {
    cache:{
        // 缓存类型,支持:memory、filesystem
        type:''filesystem
        // 缓存目录,仅类型为filsystem有效
        cacheDirectory:path.resolve(__dirname,'node_modules/.cache/webpack')
    }
}

资源模块

module.exports = {
    output:{
        assetModuleFilename:'asset/[hash:5][ext]',//在这里自定义资源文件保存的目录
    },
    module:{
        rules:{
            {
                test:/\.png/,
                type:'asset/resource',// 作用类似于file-loader
            },
            {
                test:/\.jpg/,
                type:'asset/inline',// 作用类似于url-loader 文件大小不足的场景
            },
            {
                test:/\.txt/,
                type:'asset/source',// raw-loader
            },
            {
                test:/\.gif/,
                type:'asset',//类似于url-loader
                parser:{
                    dataUrlCondition:{
                        maxSize:4*1024// 4kb以下使用data url
                    }
                }
            }
        }
    }
}