uniapp使用 uview-ui 时 总是被打包在主包中,造成主包体积已经快到2M,有什么好的解决方法吗

1,613 阅读1分钟

在使用 UniApp 开发时,uView UI 库被打包在主包中可能会导致主包体积过大。为了优化主包体积,可以采取以下几种方法:

1. 按需引入组件

uView UI 提供了按需引入组件的功能,这样可以避免将整个库都打包进主包中,只会引入使用到的组件。可以通过以下步骤实现按需引入:

安装 babel-plugin-import 插件

npm install babel-plugin-import --save-dev

配置 babel.config.js

module.exports = {
  "presets": [
    ["@babel/preset-env", {
      "modules": false
    }]
  ],
  "plugins": [
    ["import", {
      "libraryName": "uview-ui",
      "libraryDirectory": "lib",
      "style": (name) => `${name}/index.css`
    }]
  ]
}

在代码中按需引入

例如,需要使用 u-button 组件,可以这样引入:

import { uButton } from 'uview-ui';

2. 使用分包加载

UniApp 支持将项目分成多个子包,这样可以减少主包的体积。在 pages.json 中配置分包:

{
  "subPackages": [
    {
      "root": "subpackage", // 子包根目录
      "pages": [
        "index/index" // 子包中的页面路径,相对于子包根目录
      ]
    }
  ]
}

将 uView UI 相关的组件放到子包页面中,这样可以避免主包加载过多的内容。

3. 组件懒加载

使用动态组件的方式按需加载组件。在需要的时候才加载对应的组件,从而减少初始包体积:

const uButton = () => import('uview-ui/components/u-button/u-button.vue');

4. 自定义打包配置

如果以上方法仍然无法满足需求,可以考虑使用 Webpack 的自定义打包配置,对打包进行更细粒度的控制。

配置 vue.config.js

const webpack = require('webpack');

module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // 示例:忽略 moment.js 的本地化文件
    ],
    optimization: {
      splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 20000,
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name(module) {
              // 获取 node_modules 中的包名
              const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
              return `npm.${packageName.replace('@', '')}`;
            }
          }
        }
      }
    }
  }
};

以上方法可以有效减少主包体积,从而避免主包过大问题。具体可以根据项目需求和实际情况选择合适的优化方案。