search
HomeWeb Front-enduni-appOptimization of small package size of uni-app

Optimization of small package size of uni-app

Background

In the process of developing WeChat applet, as the business logic became larger and larger, some problems were highlighted.

First of all, we found that in dev mode, the local package size has reached 4m. In this case, it is no longer possible to use real machine debugging in dev mode.

Secondly, at this time, the mini program is about 1.8M after it is built. Moreover, there are still quite a few business requirements that need to be developed in the future, and the package size will definitely be larger.

At this time, I want to optimize the size of the small program package. Let me share my positioning process and solution ideas below. Although we use uni-app for development, the ideas are general. I hope it can give you some help.

How to reduce the package size

Code analysis

First analyze where the package is large.

Open the local code directory to view the file size. It can be found that js accounts for the majority of common/vendor.js and page,components.

In build compilation mode, code compression has been enabled, and other optimization methods need to be considered. At this time, you can use the webpack-bundle-analyzer plug-in. It can help analyze which js modules are in vendor.js and which modules are larger, so that we can further optimize the code

Through this plug-in, the following two problems were discovered.

Question 1: uni-app custom component mode compilation tree shaking is invalid

If you are not using uni-app for development, you can skip this section

Some modules are found through code analysis Should have been tree shaking but was packed in. It is basically certain that tree shaking does not take effect.

The same is webpack4 babel7. On the premise of not using uni-app and directly using the vue-cli create project, there is no problem with tree shaking. When using uni-app to create a new project, tree shaking is ineffective.

When I checked the babel configuration, I found that it was caused by uni-app setting modules: 'commonjs' when creating the project. After modification, the demo’s tree shaking is ok. But when I went back to the project to compile, something went wrong again. Continuing to locate, it is found that it is uni-app custom component mode compilation problem. At present, uni-app has fixed the bug I mentioned, although it has not been officially released yet.

Of course, you can solve the problem without using uni-app custom component mode compilation. uni-app also supports template template mode, but there will be some development differences and performance gaps. If you are interested, you can Read this article

Question 2: Some libraries do not support tree shaking

Some libraries (such as lodash) do not use import/export themselves, so webpack cannot tree shake them. We can optimize these libraries according to the situation.

First of all, you can find out if there is a corresponding esm version of the library on the Internet that can be replaced, such as lodash-es.

Secondly, it can be seen from the code analysis that if each module of the library is in a different file and the entry file is just a unified entry, then we can load it on demand by modifying the writing method, such as

import add from "lodash/add";
import Button from 'ant-design-vue/lib/button';复制代码

We can also use the babel-plugin-import plug-in to implement on-demand loading for those libraries. Its essence is to uniformly modify the loading path according to the configuration during compilation, without the need to manually modify the code.

In the end, if it doesn't work, then either accept it, or rewrite it yourself and contribute to the community~

Standard module development

In order to avoid the trouble of not being able to tree shaking, we are developing npm modules also need to follow certain specifications to reduce the size of the module after packaging.

Support both commonjs and es module

Our module needs to support both commonjs and es module. In this way, we can not only satisfy commonjs development users, but also support tree shaking.

How to achieve it? If your code is typescript, taking @sentry/browser as an example, you can compile the two standard codes of cjs and esm at compile time, as follows

// package.json"build": "run-s build:dist build:esm build:bundle","build:bundle": "rollup --config","build:dist": "tsc -p tsconfig.build.json","build:esm": "tsc -p tsconfig.esm.json",复制代码

Then specify two entries and no side effects flag in package.json

  "main": "dist/index.js",  "module": "esm/index.js",  "sideEffects": false,复制代码

In this way, when webpack parses the module (parsing rules), it will parse the esm directory first as needed. And perform tree shaking when no side effects are identified.

If your code itself is es6, you can also do this

"module": "src/index.js",复制代码

Third-party custom component

If a third-party WeChat custom component is used, since the reference is in json file, so webpack cannot analyze the relevant files through entry during compilation, so it will not compile, compress, etc. At this time we need to handle it ourselves. And since webpack does not handle it, tree shaking cannot be supported, so it is recommended that try to avoid referencing components in this way.

Subcontracting

Small program subcontracting is also a conventional optimization solution.

通过分析后,可以将一些较大的页面划分为子包。如果有单页依赖第三方自定义组件,而且第三方组件还挺大,也可以考虑将该页面划分为子包。也因此尽量避免将第三方自定义组件放在 globalStyle,不然没法将它放到子包去。

大图不要打包

小程序中的大图,尽量避免打包进来,应该放到 CDN 通过 url 加载。我们的做法是在开发时加载本地图片,在 CI/CD 环节自动化发布图片,并改写地址。

如何解决真机调试问题

首先还是查看编译后的文件,发现common/vendor.js巨大,足有 1.5M。其次pagescomponents也有 1.4M,而这其中占了 js 的大小又占了绝大部分。

为什么 js 文件这么大呢?主要是因为在 dev mode 默认并没有压缩,当然也没有 tree shaking。

我的选择是修改编译配置,在 dev mode 压缩 js 代码。本地代码减少到了 2M。预览大小则是减少到了 1.4M。参考配置如下:

// vue.config.js
    configureWebpack: () => {        if (isDev && isMp) {            return {
                optimization: {
                    minimize: true,
                },
            }
        }
    }复制代码

这看上去并不是个好方案,但确实简单有效。也考虑过分包,但分包并不能解决 common/vendor.js 巨大的问题,预览时包还是很大。如果有其它好的办法也欢迎留言~

更多相关免费学习推荐:微信小程序开发

The above is the detailed content of Optimization of small package size of uni-app. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
How do I handle local storage in uni-app?How do I handle local storage in uni-app?Mar 11, 2025 pm 07:12 PM

This article details uni-app's local storage APIs (uni.setStorageSync(), uni.getStorageSync(), and their async counterparts), emphasizing best practices like using descriptive keys, limiting data size, and handling JSON parsing. It stresses that lo

How do I make API requests and handle data in uni-app?How do I make API requests and handle data in uni-app?Mar 11, 2025 pm 07:09 PM

This article details making and securing API requests within uni-app using uni.request or Axios. It covers handling JSON responses, best security practices (HTTPS, authentication, input validation), troubleshooting failures (network issues, CORS, s

How do I manage state in uni-app using Vuex or Pinia?How do I manage state in uni-app using Vuex or Pinia?Mar 11, 2025 pm 07:08 PM

This article compares Vuex and Pinia for state management in uni-app. It details their features, implementation, and best practices, highlighting Pinia's simplicity versus Vuex's structure. The choice depends on project complexity, with Pinia suita

How do I use uni-app's geolocation APIs?How do I use uni-app's geolocation APIs?Mar 11, 2025 pm 07:14 PM

This article details uni-app's geolocation APIs, focusing on uni.getLocation(). It addresses common pitfalls like incorrect coordinate systems (gcj02 vs. wgs84) and permission issues. Improving location accuracy via averaging readings and handling

How do I use uni-app's social sharing APIs?How do I use uni-app's social sharing APIs?Mar 13, 2025 pm 06:30 PM

The article details how to integrate social sharing into uni-app projects using uni.share API, covering setup, configuration, and testing across platforms like WeChat and Weibo.

How do I use uni-app's easycom feature for automatic component registration?How do I use uni-app's easycom feature for automatic component registration?Mar 11, 2025 pm 07:11 PM

This article explains uni-app's easycom feature, automating component registration. It details configuration, including autoscan and custom component mapping, highlighting benefits like reduced boilerplate, improved speed, and enhanced readability.

How do I use preprocessors (Sass, Less) with uni-app?How do I use preprocessors (Sass, Less) with uni-app?Mar 18, 2025 pm 12:20 PM

Article discusses using Sass and Less preprocessors in uni-app, detailing setup, benefits, and dual usage. Main focus is on configuration and advantages.[159 characters]

How do I use uni-app's uni.request API for making HTTP requests?How do I use uni-app's uni.request API for making HTTP requests?Mar 11, 2025 pm 07:13 PM

This article details uni.request API in uni-app for making HTTP requests. It covers basic usage, advanced options (methods, headers, data types), robust error handling techniques (fail callbacks, status code checks), and integration with authenticat

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.