使用gulp解决小程序代码包过大问题

2022-07-25,,,

前言

在开发小程序项目的过程中,由于功能的不断增加导致了代码包体积的越来越大。相对其体积进行一下压缩处理,看了几篇给小程序瘦身的博客,决定给自己的项目做一套配置文件,使用gulp来支持小程序文件的编译以及上传之前压缩文件的空行之类的。

通过gulp实现代码处理,要进行一些必须文件的配置,放在小程序根目录下,然后将小程序的所有文件移至src下。

  • gulpfile.js – 使用了插件功能,支持gulp开头的插件
const gulp = require('gulp')

const SRC_DIR = './src/**/**/**/*'
const DIST_DIR = './dist/'
// Load plugins
const $ = require('gulp-load-plugins')()
const path = require('path')
const autoprefixer = require('gulp-autoprefixer')
const htmlmin = require('gulp-htmlmin')
const jsonminify = require('gulp-jsonminify2')
const gutil = require('gulp-util')
const combiner = require('stream-combiner2');
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const rename = require("gulp-rename")
const minifycss = require('gulp-minify-css')
const runSequence = require('run-sequence')
const jsonlint = require("gulp-jsonlint")
// 获取 gulp-imagemin 模块
// var imagemin = require('gulp-imagemin')


// watch
gulp.task('watch', () => {
    gulp.watch(SRC_DIR + '.js', ['jsmin'])
    gulp.watch(SRC_DIR + '.json', ['jsonmin'])
    gulp.watch('./src/res/**', ['assets'])
    gulp.watch(SRC_DIR + '.wxml', ['wxmlmin'])
    gulp.watch(SRC_DIR + '.wxss', ['wxssmin'])
})

// js
function jsmin() {
    return gulp
        .src(SRC_DIR + '.js')
        .pipe(
            babel({
                presets: ['@babel/preset-env']
            })
        )
        .pipe(
            uglify({
                compress: true
            })
        )
        .pipe(gulp.dest(DIST_DIR))
}

// json
function jsonmin() {
    return gulp
        .src(SRC_DIR + '.json')
        .pipe(jsonminify())
        .pipe(gulp.dest(DIST_DIR))
}

// 压缩图片任务
// 在命令行输入 gulp images 启动此任务
// gulp.task('images', function () {
//     // 1. 找到图片
//     gulp.src('images/1.jpg')
//     // 2. 压缩图片
//         .pipe(imagemin({
//             progressive: true
//         }))
//     // 3. 另存图片
//         .pipe(gulp.dest('dist/images'))
// });
// assets
function assets() {
    return gulp.src('./src/res/**').pipe(gulp.dest('./dist/res'))
}
// wxml
function wxmlmin() {
    return gulp
        .src(SRC_DIR + '.wxml')
        .pipe(
            htmlmin({
                collapseWhitespace: true,
                removeComments: true,
                keepClosingSlash: true,
                caseSensitive: true
            })
        )
        .pipe(gulp.dest(DIST_DIR))
}

// wxss
function wxssmin() {
    return gulp
        .src(SRC_DIR + '.wxss')
        .pipe(autoprefixer(['iOS >= 8', 'Android >= 4.1']))
        .pipe(rename(path => (path.extname = '.wxss')))
        .pipe(minifycss())
        .pipe(gulp.dest(DIST_DIR))
}
// no console
function nodebug() {
    return gulp
        .src('./dist/**/*.js')
        .pipe(stripDebug())
        .pipe(gulp.dest(DIST_DIR))
}

// build
gulp.task(
    'build',
    gulp.parallel(jsmin, jsonmin, wxmlmin, wxssmin, assets)
)

// publish
gulp.task('product', gulp.series(clean, "build", nodebug))

// clean - 不是gulp插件
const del = require('del')
function clean() {
    return del([DIST_DIR + '**'])
}
  • .babelrc – 需要配置,不然async/await不能babel
{
    "plugins": [
        "transform-strict-mode",
        "transform-es2015-modules-commonjs",
        "transform-es2015-spread",
        "transform-es2015-destructuring",
        "transform-es2015-parameters"
    ],
    "presets": [
        "@babel/preset-env"
    ]
}
  • package.json – node依赖,使用npm下载
{
  "name": "applets",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "dependencies": {
    "@babel/core": "^7.10.4",
    "@babel/preset-stage-0": "^7.8.3",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-plugin-transform-es2015-parameters": "^6.24.1",
    "babel-plugin-transform-es2015-spread": "^6.22.0",
    "babel-plugin-transform-strict-mode": "^6.24.1",
    "del": "^5.1.0",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-babel": "^8.0.0",
    "gulp-htmlmin": "^5.0.1",
    "gulp-jsonlint": "^1.3.2",
    "gulp-jsonminify2": "^1.0.2",
    "gulp-load-plugins": "^2.0.3",
    "gulp-minify-css": "^1.2.4",
    "gulp-rename": "^2.0.0",
    "gulp-uglify": "^3.0.2",
    "run-sequence": "^2.2.1",
    "stream-combiner2": "^1.1.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-strict-mode": "^7.10.4",
    "@babel/preset-env": "^7.10.4",
    "babel-plugin-transform-es2015-destructuring": "^6.23.0",
    "babel-preset-stage-0": "^6.24.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

说明

  • 流程详见 gulpfile.js 注释
  • 如果用到了less或者sass,可以配置watch,目前我的项目中没有用到,gulp的目的就是发布。如果需要实时调试可启用watch
  • 建议关闭微信的es6转es5,代码压缩
  • gulp版本的不同,会有同步和异步处理的问题
  • gulp.task 移除了三参数语法,现在不能使用数组来指定一个任务的依赖。gulp 4.0 加入了 gulp.series 和 gulp.parallel 来实现任务的串行化和并行化。
  • 任务函数中,如果任务是同步的,需要使用 done 回调。这样做是为了让 gulp 知道你的任务何时完成。
  • 如果任务是异步的,有多个方法可以标记任务完成:1. 回调,2. 返回流(Stream),3. 返回 Promise,4. 返回子进程。
  • 将task通过 js 函数的提升特性,可以将一些task定义为函数,好处就是私有化,不过就不再是gulp的命令,需要通过主task来启动。
  • 若需要同步任务,想避免显式调用done方法,可以将任务添加到串行队列执行,任务提供异步返回,保持和gulp3 一致就行。

可能出现的问题

  • 小程序组件间传值和事件,不要使用大驼峰,通过gulp-htmlmin压缩wxml代码时,pages内的页面会被转为全小写
    • js大小写是敏感的,html大小写是不敏感的,因此属性和事件的传递建议使用小写
    • 不使用gulp-htmlmin代码压缩wxml文件
  • 小程序border为1rpx时提供gulp-minify-css压缩后,1rpx就变成了0,因此需要使用1px作为border的宽度

本文地址:https://blog.csdn.net/qq_40665861/article/details/112260943

《使用gulp解决小程序代码包过大问题.doc》

下载本文的Word格式文档,以方便收藏与打印。