gulp构建小程序的方法步骤


Posted in Javascript onMay 31, 2019

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

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

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

ts => js
sass=>wxss
wxml=>wxml
json=>json

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

最终效果:

gulp构建小程序的方法步骤

gulp构建小程序的方法步骤

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;

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

Javascript 相关文章推荐
jquery动态改变form属性提交表单
Jun 03 Javascript
JS实现仿google、百度搜索框输入信息智能提示的实现方法
Apr 20 Javascript
js实现人才网站职位选择功能的方法
Aug 14 Javascript
jQuery添加和删除指定标签的方法
Dec 16 Javascript
javascript 继承学习心得总结
Mar 17 Javascript
jQuery UI仿淘宝搜索下拉列表功能
Jan 10 Javascript
纯js实现画一棵树的示例
Sep 05 Javascript
JS生成随机打乱数组的方法示例
Dec 23 Javascript
axios实现简单文件上传功能
Sep 25 Javascript
微信小程序绑定手机号获取验证码功能
Oct 22 Javascript
在Vue中使用Echarts实例图的方法实例
Oct 10 Javascript
Vue中ref和$refs的介绍以及使用方法示例
Jan 11 Vue.js
jQuery实现动态加载(按需加载)javascript文件的方法分析
May 31 #jQuery
自定义javascript验证框架示例【附源码下载】
May 31 #Javascript
vue spa应用中的路由缓存问题与解决方案
May 31 #Javascript
JS实现处理时间,年月日,星期的公共方法示例
May 31 #Javascript
一文了解vue-router之hash模式和history模式
May 31 #Javascript
vue App.vue中的公共组件改变值触发其他组件或.vue页面监听
May 31 #Javascript
微信小程序环境下将文件上传到OSS的方法步骤
May 31 #Javascript
You might like
php 一元分词算法
2009/11/30 PHP
mac下使用brew配置环境的步骤分享
2011/05/23 PHP
解析PHP中的file_get_contents获取远程页面乱码的问题
2013/06/25 PHP
php pki加密技术(openssl)详解
2013/07/01 PHP
thinkPHP实现递归循环栏目并按照树形结构无限极输出的方法
2016/05/19 PHP
Yii2框架可逆加密简单实现方法
2017/08/25 PHP
PHP使用file_get_contents发送http请求功能简单示例
2018/04/29 PHP
Jquery ajax不能解析json对象,报Invalid JSON错误的原因和解决方法
2010/03/27 Javascript
javascript一元操作符(递增、递减)使用示例
2013/08/07 Javascript
js读写cookie实现一个底部广告浮层效果的两种方法
2013/12/29 Javascript
ext中store.load跟store.reload的区别示例介绍
2014/06/17 Javascript
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
jQuery实现控制文字内容溢出用省略号(…)表示的方法
2016/02/26 Javascript
Angular.Js的自动化测试详解
2016/12/09 Javascript
jQuery实现获取table中鼠标click点击位置行号与列号的方法
2017/10/09 jQuery
vue 虚拟dom的patch源码分析
2018/03/01 Javascript
angular4应用中输入的最小值和最大值的方法
2019/05/17 Javascript
JS实现小米轮播图
2020/09/21 Javascript
Python 自动安装 Rising 杀毒软件
2009/04/24 Python
python 自动提交和抓取网页
2009/07/13 Python
python3实现读取chrome浏览器cookie
2016/06/19 Python
python对象及面向对象技术详解
2016/07/19 Python
Python实现二维数组按照某行或列排序的方法【numpy lexsort】
2017/09/22 Python
Python中数组,列表:冒号的灵活用法介绍(np数组,列表倒序)
2018/04/18 Python
Python 给某个文件名添加时间戳的方法
2018/10/16 Python
外贸业务员求职信范文
2013/12/12 职场文书
学生自我鉴定模板
2013/12/30 职场文书
工会主席岗位责任制
2014/02/11 职场文书
趣味比赛活动方案
2014/02/15 职场文书
学生个人总结范文
2015/02/15 职场文书
新年晚会开场白
2015/05/29 职场文书
2015年村级财务管理制度
2015/08/04 职场文书
2016学习依法治国心得体会
2016/01/15 职场文书
升职感谢领导的话语及升职感谢信
2019/06/24 职场文书
JS + HTML 罗盘式时钟的实现
2021/05/21 Javascript
Typescript类型系统FLOW静态检查基本规范
2022/05/25 Javascript