likes
comments
collection
share

Webpack5 模块联邦

作者站长头像
站长
· 阅读数 20

概述

1.模块联邦基于Webpack5基础上的一款插件,具备Webpack最新特性

Tree Shaking 更优Node.js polifill 给为按需加载缓存机制优化优化打包命名算法

2.模块联邦可以将应用划分为更小的应用块,比如头部导航或侧边栏,也可以是数据获取逻辑的逻辑组件3.每个应用块由不同的组开发4.应用或应用快共享其他应用块或者库

新增配置项

 module.exports ={
    watch:true, // 增量编译
    cache{      // 缓存
+     type:'filesystem' // memory filesystem
    },
    optimization:{
+     moduleIds:'natural',//模块名称的生成规则
+     chunkIds:'natural'  //代码块名称的生成规则
    },
    output:{
      filename:'[name.js]',    //入口代码块文件名的生成规则
      chunkFilename:'[name.js]'//非入口模块的生成规则
    },
    pulages:[
      ....
+     {test:/\.png$/,type:'asset/resource'},//对标file-loader
+     {test:/\.ico$/,type:'asset/inline'},  //对标url-loader 模块的大小 < limit base64字符串
+     {test:/\.txt$/,type:'asset/source'},  //对标raw-loader 源文件读取
+     {test:/\.jpg$/,type:'asset',parser{dataurlCoundition:{maxSize:4*1024}}} // type:'asset' 表示需要webpack打包的资源
      ....
    ]
 }
optimization moduleIds:1.natural 按使用顺序的数字ID2.named 方便调试的高可读性ID3.deterministic 根据模块名称生成简短的hash值4.size 根据模块大小生成的数字id

模块联邦

module.exports = {
   ...
   plugins:[
    ...
+    new ModuleFederationPlugin({
+    name:'remoteVar',
+    filename:'remoteEntry.js',
+    exposes:{
+     './NewsList':'./src/NewsList'
+    },
+    remotes:{
+     host:'hostVar@http://localhost:8081/remoteEntry.js'
+    },
+    shared:['react','react-dom']    
   ]
}
name 必须【唯一ID】作为输出的模块名,使用的时通过 ${name}/${expose} 的方式使用,暴露在window中的全局对象;library 必须【变量】其中这里的 name 为作为 umd 的 name;filename 可选【暴露】构建出的文件名称exposes 可选【暴露】组件,表示作为 Remote 时,export 哪些属性被消费;remotes 可选【引用】表示作为 Host 时,去消费哪些 Remote;shared 可选【共享】共享池任何一方加载过,另外一方就不需要再加载了;

Webpack5 模块联邦

场景方案

  • 基于React CRA的工程升级webpack
    npx create-react-app my-app --template webpack-5-typescript --scripts-version webpack-5-react-scripts