侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

gulp构建小程序的方法步骤

微信(小程序)  /  管理员 发布于 3年前   303

目前来说,对于构建小程序的,类似taro这些框架,生态已经挺完善的了,没有什么必要再搞一套来折腾自己。但是,我司的小程序,是很早之前就开发的,我们负责人当时信不过这些开源的框架,于是自己用webpack搞了一套框架,但有一个比较严重的问题,有一些文件依赖重复打包了,导致小程序包体积比较大。

持续了一个多月,主包体积在2M左右徘徊,开发都很难做下去。我们负责人终于受不了了,给了我个任务,让我写一个构建小程序的工具,减少小程序包体积。

我们现在的框架对比一下原生小程序,其实差别不大,无非就是

 ts => jssass=>wxsswxml=>wxmljson=>json

由于我司小程序基础库是1.9.8的,不支持构建npm,所以node_modules的依赖包以及依赖路径需要自己处理,于是写了一个babel插件 babel-plugin-copy-npm。
这么一想,其实不难,而且单文件编译,那不是gulp的强项吗!!!

最终效果:

而且由于增量更新,只修改改变的文件,所以编译的速度非常快。

项目地址:https://github.com/m-Ryan/ry-wx

最终流程大概如下:清除dist目录下的文件 => 编译文件到dist目录下=> 开发模式监听文件更改,生产环境压缩文件。

一、清除dist目录下的文件 (clean.js)

const del = require('del');const fs = require('fs');const path = require('path');const cwd = process.cwd();module.exports = function clean() {  if (!fs.existsSync(path.join(cwd, 'dist'))) {    fs.mkdirSync('dist');    return Promise.resolve(null);  }  return del([ '*', '!npm' ], {    force: true,    cwd: path.join(cwd, 'dist')  });};

二、编译文件

1.编译typescript(compileJs.js)

const gulp = require('gulp');const { babel } = require('gulp-load-plugins')();const path = require('path');const cwd = process.cwd();module.exports = function compileJs(filePath) {  let file = 'src/**/*.ts';  let dist = 'dist';  if (typeof filePath === 'string') {    file = path.join(cwd, filePath);    dist = path.dirname(file.replace(/src/, 'dist'));  }  return gulp.src(file).pipe(babel()).pipe(gulp.dest(dist));};

2.编译sass(compileSass.js)

const gulp = require('gulp');const { sass, postcss, rename } = require('gulp-load-plugins')();const path = require('path');const cwd = process.cwd();const plugins = [  require('autoprefixer')({    browsers: [ 'ios >= 8', 'ChromeAndroid >= 53' ],    remove: false,    add: true  }),  require('postcss-pxtorpx')({    multiplier: 2,    propList: [ '*' ]  })];module.exports = function compileSass(filePath) {  let file = 'src/**/*.scss';  let dist = 'dist';  if (typeof filePath === 'string') {    file = path.join(cwd, filePath);    dist = path.dirname(file.replace(/src/, 'dist'));  }  return gulp    .src(file)    .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))    .pipe(postcss(plugins))    .pipe(      rename({        extname: '.wxss'      })    )    .pipe(gulp.dest(dist));};

编译json,wxml,由于需要压缩,所以需要分开处理

(copyJson.js)

const gulp = require('gulp');module.exports = function copyJson() {  let file = 'src/**/*.json';  let dist = 'dist';  if (typeof filePath === 'string') {    file = path.join(cwd, filePath);    dist = path.dirname(file.replace(/src/, 'dist'));  }  return gulp.src([ file ]).pipe(gulp.dest(dist));};

(copyWxml.js)

const gulp = require('gulp');const minifyHtml = require('gulp-html-minify');module.exports = function copyWxmlFiles() {  let file = 'src/**/*.wxml';  let dist = 'dist';  if (typeof filePath === 'string') {    file = path.join(cwd, filePath);    dist = path.dirname(file.replace(/src/, 'dist'));  }  return gulp.src(file).pipe(minifyHtml()).pipe(gulp.dest(dist));};

4.拷贝其他静态资源,例如字体、图片

(copyAssets.js)

const gulp = require("gulp");module.exports = function copyAssets() { let file = "src/**/**"; let dist = "dist"; if (typeof filePath === "string") {  file = path.join(cwd, filePath);  dist = path.dirname(file.replace(/src/, "dist")); } return gulp  .src([   file,   "!**/*.json",   "!**/*.ts",   "!**/*.js",   "!**/*.scss",   "!**/*.wxml"  ])  .pipe(gulp.dest(dist));};

5.引入文件(gulpfile.js)

const gulp = require("gulp");const clean = require("./build/clean");const compileJs = require("./build/compileJs");const compileSass = require("./build/compileSass");const copyJson = require("./build/copyJson");const copyWxml = require("./build/copyWxml");const copyAssets = require("./build/copyAssets");const fs = require("fs-extra");const path = require("path");const chalk = require("chalk");const cwd = process.cwd();const dayjs = require("dayjs");const tasks = [ clean, gulp.parallel([compileJs, compileSass, copyJson, copyWxml]), copyAssets];if (process.env.NODE_ENV === "development") { tasks.push(watch);}gulp.task("default", gulp.series(tasks));gulp.task("watch", watch);function watch() { console.log(chalk.blue(`正在监听文件... ${getNow()}`)); const watcher = gulp.watch("src/**/**"); watcher.on("change", function(filePath, stats) {  compile(filePath); }); watcher.on("add", function(filePath, stats) {  compile(filePath); }); watcher.on("unlink", function(filePath, stats) {  let distFile = filePath.replace(/^src\b/, "dist");  let absolutePath = "";  if (distFile.endsWith(".ts")) {   distFile = distFile.replace(/.ts$/, ".js");  } else if (distFile.endsWith(".scss")) {   distFile = distFile.replace(/.scss$/, ".wxss");  }  absolutePath = path.join(cwd, distFile);  if (fs.existsSync(absolutePath)) {   fs.unlinkSync(absolutePath);   console.log(    chalk.yellow(`删除文件:${path.basename(distFile)} ${getNow()}`)   );  } });}function compile(filePath) { console.info(  chalk.green(`编译完成:${path.basename(filePath)} ${getNow()}`) ); if (filePath.endsWith(".ts")) {  compileJs(filePath); } else if (filePath.endsWith(".scss")) {  compileSass(filePath); } else if (filePath.endsWith(".wxml")) {  copyWxml(filePath); } else if (filePath.endsWith(".json")) {  copyJson(filePath); } else {  copyAssets(filePath); }}function getNow() { return dayjs().format("HH:mm:ss");}

babel的配置如下.babelrc.js

const babelOptions = {  presets: [ '@babel/preset-typescript', [ '@babel/env' ] ],  plugins: [    'lodash',    [      '@babel/plugin-proposal-decorators',      {        legacy: true      }    ],    'babel-plugin-add-module-exports',    [      '@babel/plugin-transform-runtime',      {        corejs: false,        helpers: true,        regenerator: true,        useESModules: false      }    ],    [      'module-resolver',      {        root: [ '.' ],        alias: {          '@': './src'        }      }    ],    [      'babel-plugin-copy-npm',      {        rootDir: 'src',        outputDir: 'dist',        npmDir: 'npm',        format: 'cjs',        strict: false,        minify: true,        loose: true,        cache: true      }    ]  ]};if (process.env.NODE_ENV === 'production') {  babelOptions.presets.unshift([    'minify',    {      mangle: {        exclude: [ 'wx', 'module', 'exports', '__wxConfigx', 'process', 'global' ]      },      keepFnName: true    }  ]);}module.exports = babelOptions;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

  • 小程序如何构建骨架屏
  • mpvue构建小程序的方法(步骤+地址)
  • 微信小程序 swiper组件构建轮播图的实例


  • 上一条:
    微信小程序环境下将文件上传到OSS的方法步骤
    下一条:
    微信小程序mpvue点击按钮获取button值的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 小程序开发之跳转微信直播示例api(0个评论)
    • 在uni_app中开发小程序之常用功能示例代码汇总(0个评论)
    • 小程序开发之多端框架:taro(0个评论)
    • 微信小程序前端使用七牛云官方SDK上传七牛云代码示例(0个评论)
    • 百度小程序审核未通过,真机审核存在点击返回键退出小程序...解决方式之一tabBar(0个评论)
    • 近期文章
    • windows系统中安装FFMpeg及在phpstudy环境php7.3 + php-ffmpeg扩展的使用流程步骤(0个评论)
    • 在go语言中对浮点的数组、切片(slice)进行正向排序和反向排序(0个评论)
    • 在go语言中对整数数组、切片(slice)进行排序和反向排序(0个评论)
    • 在go语言中对字符串数组、切片(slice)进行排序和反向排序(0个评论)
    • 最新国内免注册ChatGPT体验站_ChatGPT镜像站访问链接地址2023/3/28持续更新(0个评论)
    • 在Laravel项目中的实现无密码认证之:发送邮箱链接授权(0个评论)
    • 在go语言中使用GoRoutines实现高性能并发批量调用api示例(0个评论)
    • Docker撤回受争议的收费方案,又可以继续使用docker了(0个评论)
    • 在go语言生成唯一ID之SnowFlake算法(0个评论)
    • ChatGPT再出新功能,推出插件功能,能联网、搜索了(0个评论)
    • 近期评论
    • 博主 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..
    • xiaoB 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..
    • BUG4 在

      你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..
    • 博主 在

      go语言+beego框架中获取get,post请求的所有参数中评论 @ t1  直接在router.go文件中配就ok..
    • Jade 在

      如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
    • 2017-10
    • 2018-01
    • 2020-03
    • 2021-06
    • 2021-10
    • 2022-03
    • 2023-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客