欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gulp构建小程序的方法步骤

程序员文章站 2023-12-18 16:49:28
目前来说,对于构建小程序的,类似taro这些框架,生态已经挺完善的了,没有什么必要再搞一套来折腾自己。但是,我司的小程序,是很早之前就开发的,我们负责人当时信不过这些开源的...

目前来说,对于构建小程序的,类似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;

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

上一篇:

下一篇: