iuap-design / blog

📖 用友网络大前端技术团队博客
Apache License 2.0
939 stars 120 forks source link

webpack4 升级或使用的几点采坑记录 #262

Open kvkens opened 6 years ago

kvkens commented 6 years ago
  1. 如果使用全局的webpack4.x,那么需要安装 npm install webpack-cli -D
  2. webpack.config.js 新增mode参数,developmentproduction
  3. 默认入口文件是./src/index.js,默认输出文件./dist/main.js。
  4. extract-text-webpack-plugin需要升级rc版本才不会报错
  5. 不想用extract-text-webpack-plugin那么就是用官方新增加的mini-css-extract-plugin
  6. webpack4.x中webpack.config.js这样的配置文件不是必须的。
  7. 提取公共模块,webpack4去除了CommonsChunkPlugin,使用SplitChunksPlugin作为替代
  8. 新增optimization字段
  9. 开发webpack插件的时候,内置的call不能使用,建议更换最新的事件机制

关于优化这块,贴出一些配置和翻译可以看一下参考,具体需要实验才能得出最终结论:

  optimization: {
    //提取公共模块,webpack4去除了CommonsChunkPlugin,使用SplitChunksPlugin作为替代
    //主要用于多页面
    //例子代码 https://github.com/webpack/webpack/tree/master/examples/common-chunk-and-vendor-chunk
    //SplitChunksPlugin配置,其中缓存组概念目前不是很清楚
    splitChunks: {
      // 表示显示块的范围,有三个可选值:initial(初始块)、async(按需加载块)、all(全部块),默认为all;
      chunks: "all",
      // 表示在压缩前的最小模块大小,默认为0;
      minSize: 30000,
      //表示被引用次数,默认为1
      minChunks: 1,
      //最大的按需(异步)加载次数,默认为1;
      maxAsyncRequests: 3,
      //最大的初始化加载次数,默认为1;
      maxInitialRequests: 3,
      // 拆分出来块的名字(Chunk Names),默认由块名和hash值自动生成;设置ture则使用默认值
      name: true,
      //缓存组,目前在项目中设置cacheGroup可以抽取公共模块,不设置则不会抽取
      cacheGroups: {
        //缓存组信息,名称可以自己定义
        commons: {
          //拆分出来块的名字,默认是缓存组名称+"~" + [name].js
          name: "test",
          // 同上
          chunks: "all",
          // 同上
          minChunks: 3,
          // 如果cacheGroup中没有设置minSize,则据此判断是否使用上层的minSize,true:则使用0,false:使用上层minSize
          enforce: true,
          //test: 缓存组的规则,表示符合条件的的放入当前缓存组,值可以是function、boolean、string、RegExp,默认为空;
          test: ""
        },
        //设置多个缓存规则
        vendor: {
          test: /node_modules/,
          chunks: "all",
          name: "vendor",
          //表示缓存的优先级
          priority: 10,
          enforce: true
        }
      }
    }
  }
dongyuanxin commented 6 years ago

您好,最近刚接触webpack,有两个问题想请教您:

  1. vendor缓存组中:如果test参数配置为 /[\\/]node_modules[\\/]/ 或者 /node_modules/均可。但是,设置成'node_modules'__dirname + "/node_modules"都不可以,为什么呢?官网不是说可以设置为字符串形式吗?

  2. vendor缓存组中:如果不配置priority,会和commons打包在一起,作为一个chunk,而不是2个。不设置优先级,就会自动被打包在一起吗?

dongyuanxin commented 6 years ago

I read the document again . And find it : "A module can be assigned to multiple cache groups. The optimization then prefers the cache group with the higher priority (priority option) or that one that forms bigger chunks.".

So, always set 'priority' , right?

erichui commented 5 years ago

您好,最近刚接触webpack,有两个问题想请教您:

  1. vendor缓存组中:如果test参数配置为 /[\\/]node_modules[\\/]/ 或者 /node_modules/均可。但是,设置成'node_modules'__dirname + "/node_modules"都不可以,为什么呢?官网不是说可以设置为字符串形式吗?
  2. vendor缓存组中:如果不配置priority,会和commons打包在一起,作为一个chunk,而不是2个。不设置优先级,就会自动被打包在一起吗?

1:字符串的话是不是应该是'/node_modules' _dirname + '../node_modules' 2: 自定义的chunk最好设置一下优先级吧,不然默认chuank的size肯定相对会大一点,就会打包到默认chunk里面