乾坤微前端优化 (二)_乾坤微前端性能优化-程序员宅基地

技术标签: 微前端  webpack  

乾坤微前端优化(一)的基础上再次进行了优化,本次优化的是子模块共同的配置,以及dll包。
 

DllReferencePlugin配置

直接上dll配置的代码:

const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');

// antd 模块
const antdModules = ['form', 'upload',
  'switch', 'button',
  'input', 'table',
  'message', 'modal',
  'tooltip', 'select',
  'tree-select', 'date-picker',
  'input-number', 'radio',
  'popconfirm', 'grid'
];
// ['echarts/lib/echarts', 
// 'echarts/lib/chart/line', 'echarts/lib/chart/bar', 'echarts/lib/chart/pie',
// 'echarts/lib/component/tooltip', 'echarts/lib/component/grid', 'echarts/lib/component/title', 'echarts/lib/component/legend']
module.exports = {
  mode: 'production',
  entry: {
    echarts: ['echarts'],
    xlsx: ['xlsx'],
    antd: antdModules.map(item => `antd/es/${item}`).concat(['history', 'react-router-dom', 'react-router']), // 链接到这里是因为打包会产生react.js代码
    vendor: ['axios', 'scroll-into-view-if-needed']
  },
  output: {
    filename: 'dll.[name].js',
    path: path.resolve(__dirname, '../dll'),
    // 全局变量名称
    library: '[name]_library'
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, '../dll/**/*')]
    }),
    new webpack.DllPlugin({
      // 和library 一致,输出的manifest.json中的name值
      name: '[name]_library',
      // path 指定manifest.json文件的输出路径
      path: path.resolve(__dirname, '../dll/[name]-manifest.json'),
    }),
    // new BundleAnalyzerPlugin(),
    new FriendlyErrorsPlugin(),
  ],


  stats: 'errors-only',

  // 关闭文件过大检查
  performance: {
    hints: false
  },
}

以上配置基本满足要求了。

缺点:不能自动按需加载,需要自己配置。

比如说我自己配置的antd按需加载,自己写加载的路径。

ps:echarts按需加载不知道怎么写。
 

webpack.config配置

主应用的配置基本不变,第二版主要是改变了子应用的webpack配置,把子应用的webpack配置放到了基础模板中,后续子应用直接从基础模板中导入webpack配置并合并配置。

公共配置

webpack.config.base

// webpack.config.base.js
const path = require('path');
// 动态生成html文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 清除文件夹
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// 抽取css代码
const MiniCssRxtractPlugin = require('mini-css-extract-plugin');
// 控制台删除无效的打印
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
// 压缩css
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// 给模块做缓存
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
// 生产包分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// js压缩
const TerserPlugin = require('terser-webpack-plugin');
//
const Webpack = require('webpack');
const { isEnvProduction, isEnvDevelopment, lessLoader, cssLoader, tsxLoader, sourceLoader,  ttfLoader } = require('./utils');
// 引入配置文件
const { dllReferencePlugins } = require('./path.json');

module.exports = {
  // 入口
  entry: "./src/index.tsx",

  // 生产模式下关闭map文件
  devtool: isEnvProduction ? "none" : "source-map",

  // 解析相关
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
    alias: {
      // '@': resolve('../src')
    }
  },

  // 模块
  module: {
    rules: [tsxLoader, isEnvProduction ? null : sourceLoader, cssLoader, lessLoader, ttfLoader].filter(Boolean),
  },

  // 插件
  plugins: [
    new MiniCssRxtractPlugin({
      filename: `static/styles/[name]${isEnvProduction ? '.[hash:8]' : ''}.css`,
      chunkFilename: `static/styles/[name]${isEnvProduction ? '.[hash:8]' : ''}.css`
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      inject: true,
      minify: {
        removeComments: true,                   // 移除注释
        collapseWhitespace: true,               // 移除空格
      }
    }),

    // 导入
    ...dllReferencePlugins.map(item => new Webpack.DllReferencePlugin({
      manifest: path.join(__dirname, `../../cstmr-paltform-base/dll/${item}-manifest.json`)
    })),

    isEnvDevelopment && new Webpack.HotModuleReplacementPlugin(),
    new HardSourceWebpackPlugin(),
    isEnvProduction && new CleanWebpackPlugin(),
    new FriendlyErrorsPlugin(),
    isEnvProduction ? new BundleAnalyzerPlugin({
      analyzerPort: Math.floor(Math.random() * 9000) + 1000
    }) : null,
  ].filter(Boolean),

  stats: 'errors-only',

  // // 关闭文件过大检查
  performance: {
    hints: false
  },

  // 优化
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        antd: {
          test: /[\\/]node_modules[\\/]antd[\\/]/,
          name: 'antd',
          priority: 10 // 需要级别高点
        },
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          priority: 8
        }
      }
    },

    runtimeChunk: {
      name: 'runtime'
    },

    minimizer: [
      new TerserPlugin({
        terserOptions: {
          parse: {
            // we want terser to parse ecma 8 code. However, we don't want it
            // to apply any minfication steps that turns valid ecma 5 code
            // into invalid ecma 5 code. This is why the 'compress' and 'output'
            // sections only apply transformations that are ecma 5 safe
            // https://github.com/facebook/create-react-app/pull/4234
            ecma: 8,
          },
          compress: {
            ecma: 5,
            warnings: false,
            // Disabled because of an issue with Uglify breaking seemingly valid code:
            // https://github.com/facebook/create-react-app/issues/2376
            // Pending further investigation:
            // https://github.com/mishoo/UglifyJS2/issues/2011
            comparisons: false,
            // Disabled because of an issue with Terser breaking valid code:
            // https://github.com/facebook/create-react-app/issues/5250
            // Pending futher investigation:
            // https://github.com/terser-js/terser/issues/120
            inline: 2,
          },
          mangle: {
            safari10: true,
          },
          output: {
            ecma: 5,
            comments: false,
            // Turned on because emoji and regex is not minified properly using default
            // https://github.com/facebook/create-react-app/issues/2488
            ascii_only: true,
          },
        },
        // Use multi-process parallel running to improve the build speed
        // Default number of concurrent runs: os.cpus().length - 1
        // Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
        // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
        parallel: false,
        // Enable file caching
        cache: true,
        sourceMap: false,
      }),
      new OptimizeCSSAssetsPlugin({
        cssProcessor: require('cssnano'), //引入cssnano配置压缩选项
        cssProcessorOptions: {
          discardComments: { removeAll: true }
        },
        canPrint: false
      })
    ]
  },

  // devServer 配置
  devServer: {
    historyApiFallback: true,
    port: '9001',
    hot: true,
    hotOnly: true,
    inline: true,
    headers: {
      "Access-Control-Allow-Origin": "*"
    },
    proxy: {
      '/api': {
        target: 'https://dev.mhealth100.com',
        changeOrigin: true,     // 跨域
        pathRewrite: {
          '^/api': '/'
        }
      },
    },
  }
}
// path.json
{
  "root": {
    "development": "/",
    "production": "/dist"
  },
  "dllReferencePlugins": [
    "echarts",
    "xlsx",
    "vendor",
    "antd"
  ]
}

webpack.config

const path = require('path');
const resolve = dir => path.resolve(__dirname, dir);
// 选取最后一个值
const mode = process.argv.slice(-1)[0];
const isEnvProduction = mode === 'production';
const { merge } = require('webpack-merge');
// 
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');

const webpackConfg = require('../../base-template/webpack-config/webpack.config');
const packageName = require('../package.json').name;
const { root: { production: pathName } } = require('./../../base-template/webpack-config/path.json');

// 图片解析
const imageLoader = {
  test: /\.(png|svg|jpe?g)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 1024 * 10,
        name: `/images/[name].[hash:7].[ext]`,
        publicPath: isEnvProduction ? `${pathName}/${packageName}/` : '/'
      }
    }
  ]
}

module.exports = merge([webpackConfg, {
  // 出口
  output: {
    filename: `static/js/[name]${isEnvProduction ? '.[hash:8]' : ''}.js`,
    path: path.join(__dirname, `../${packageName}`),
    publicPath: isEnvProduction ? `${pathName}/${packageName}/` : "/",
    library: `${packageName}`,
    libraryTarget: 'umd',
    jsonpFunction: `webpackJsonp_${packageName}`,
  },

  // 模块
  module: {
    rules: [imageLoader],
  },

  plugins: [new WatchMissingNodeModulesPlugin(resolve('../node_modules'))],

  resolve: {
    alias: {
      '@': resolve('../src')
    }
  },
  devServer: {
    port: '9001'
  }
}])

注意:这个需要重新定义文件的相对地址,比如说pathName和packageName等数据,重新定义resolve,不然他会打包到base-template模板的代码,而不会打包当前子应用的代码。

 

打包上线

至此,打包上线即可。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/besttoby01/article/details/108573902

智能推荐

【2024-01-14】各种安卓模拟器安装magisk(magisk-delta) 雷电、蓝叠、MuMu、逍遥、夜神_magisk terminal emulator-程序员宅基地

文章浏览阅读6.9k次,点赞36次,收藏44次。使用Magisk Delta在各种模拟器安装Magisk到System分区的过程_magisk terminal emulator

大数据之Hive:Hive中日期时间函数_hive date format函数-程序员宅基地

文章浏览阅读1.7k次,点赞2次,收藏5次。目录1.date_format函数(根据格式整理日期)2.date_add函数(加减日期),date_sub,date_diff3.next_day函数4.last_day函数(求当月最后一天日期)1.date_format函数(根据格式整理日期)hive (gmall)> select date_format('2021-03-20','yyyy-MM');2020-03备注:与mysql中date_format函数的不同之处是:在hive中,可以指定为"yyyy-MM",在mysql中必_hive date format函数

转贴 解决sd卡的读写问题_hc32f460 sd 卡 micro sd卡-程序员宅基地

文章浏览阅读1.6k次。最近sd卡读写出了问题,参考一篇网志解决。http://sns.linuxpk.com/space-1717-do-blog-id-15748.html 在embedded linux下插上一个U盘,在/dev/scsi/ 目录下,出现了4个part 。把该U盘插在pc机,在windows下_hc32f460 sd 卡 micro sd卡

qsort函数(c语言库函数)_qsqrt位于什么库中-程序员宅基地

文章浏览阅读643次,点赞19次,收藏9次。qsort函数的基本概念及代码示例_qsqrt位于什么库中

flink 1.13.1配置报错的解决过程_main error could not create plugin of type class o-程序员宅基地

文章浏览阅读4.3k次。部署flink提交客户端的时间报错如下:提示/tmp下无权限flink@dbos-bigdata-flink004 ~]$ flink run -m yarn-cluster -yjm 1024 -ytm 4096 /opt/flink/examples/batch/WordCount.jarSLF4J: Class path contains multiple SLF4J bindings.SLF4J: Found binding in [jar:file:/opt/flink-1.13.1/l._main error could not create plugin of type class org.apache.logging.log4j.co

大数据概况及Hadoop生态系统_hadoop系统固有功能分析-程序员宅基地

文章浏览阅读308次。一、初识大数据了解大数据是什么。了解大数据的特性。了解大数据带给企业哪些方面的挑战。1.大数据的基本概念大数据(big data),指无法在一定时间范围内用常规软件工具进行捕捉、管理和处理的数据集合,是需要新处理模式才能具有更强的决策力、洞察发现力和流程优化能力的海量、高增长率和多样化的信息资产。2.大数据的特性(1)4V特征:a. Volume(大数据量):90% 的数据是过去两年产生b.Velocity(速度快):数据增长速度快,时效性高c.Variety(多样化):数据种类和来源多_hadoop系统固有功能分析

随便推点

html页面播放rtsp流媒体_html播放rtsp流-程序员宅基地

文章浏览阅读2.7k次。采取的方案node.js + Ffmpeg + jsmpeg工具node.js 下载路径https://pan.baidu.com/s/1DYnPW28hZz-I56jOopwxGQFfmpeg下载路径:https://pan.baidu.com/s/1KEGIYrRVLnLyDx1hwx4yBAjsmpeg下载路径:https://pan.baidu.com/s/1p5SnShAlTB..._html播放rtsp流

黑马程序员--Objective-C——面向对象-程序员宅基地

文章浏览阅读319次。------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------一、面向对象的理解 面向对象 Object Oriented,简称OO,面向对象的思想,即“万物皆对象”。解决问题思考的是需要用的对象,用这些对象的属性功能去解决问题,而不是去思考解决问题的步骤。把具有相似功能和属性的对象抽象为类,即一个类可以有很多对象,而一个对

由繁化简 Q-Automation助力自动化测试管理-程序员宅基地

文章浏览阅读383次,点赞8次,收藏7次。Q-Automation是基于ATX的自动化测试管理软件,用于测试电子控制单元(ECU)。该软件支持诊断协议层测试和诊断功能测试,且只需填写Excel表格,即可实现半自动化测试需求,从而缩短用户的测试周期。此外,使用ODX/OTX标准化工具,可在支持多种测试硬件的同时,减少测试软件的兼容性问题,还便于与其它工具共享数据。

【试水CAS-4.0.3】第04节_CAS服务端通过数据库认证用户_cas如何数据库管理 serviceid-程序员宅基地

文章浏览阅读5.5k次。完整版见https://jadyer.github.io/2015/07/18/sso-cas-login-db/_cas如何数据库管理 serviceid

C# 调用RESTFul接口_c#调用restful接口-程序员宅基地

文章浏览阅读3.2k次。c# Restful_c#调用restful接口

HOG特征——行人识别_hog特征识别行人 peopledetector=vision.peopledetector; i=-程序员宅基地

文章浏览阅读1.8k次,点赞4次,收藏24次。HOG特征简介HOG 全称为 Histogram of Oriented Gradients ,即方向梯度的直方图。HOG 是由 Navneet Dalal & Bill Triggs 在 CVPR 2005发表的论文中提出来的,目的是为了更好的解决行人检测的问题。先来把这几个字拆开介绍,首先,梯度的概念和计算梯度的方法已经在前一篇文章中介绍了,方向梯度就是说梯度的方向我们也要利用上,..._hog特征识别行人 peopledetector=vision.peopledetector; i=imread(

推荐文章

热门文章

相关标签