使用gulp自定义合并Amd模块

1,439 阅读1分钟
1. 简单介绍一下,这个主要是项目上使用的就是AMD规范,自己定义了许多模块。有时候不同的人需要不同的模块啊,不能一次合并到一个文件中,这样文件太冗余。所以就想到每个人只把自己需要的那个模块合并。于是就有了下面的文件
let gulp = require('gulp'),
  gulpUglify = require('gulp-uglify'),
  amdOptimize = require('amd-optimize'),
  concat = require('gulp-concat'),
  filter = require('gulp-filter'),
  lazypipe = require('lazypipe'),
  foreach = require('gulp-foreach'),
  logger = require('gulp-logger'),
  gulpError = require('gulp-error'),
  babel = require('gulp-babel'),
  argv = require('yargs').argv;


/**
 * 函数定义:获取文件路径并使用正则匹配文件
 * @param stream
 * @param file
 * @returns {*|*}
 * @author Visupervi
 * @Email visupervi@outlook.com
 */
function getSelfAmd(stream, file) {
  console.log(file.path);
  let moduleId = file.path.match(/report\.(.+)\.js/)[1];
  console.log(moduleId);
  return stream.pipe(amdOptimize(`report.${moduleId}`, {
    exclude:[jquery]
  }))
}

let gatherCustom = lazypipe()
  .pipe(foreach, getSelfAmd);
gulp.task("custom", () => {
  let files = argv.c;
  if (!files) {
    throw new gulpError({
      plugin: 'custom',
      message: 'please provide a list of the components to be included'
    });
  }
  if (files.indexOf(',') !== -1) {
    files = `{${files}}`;
  }
  let included = [];
  return gulp.src(`report.${files}.js`)
    .pipe(babel({  //转换es6
      presets: ["es2015"]
    }))
    .pipe(gatherCustom())
    .pipe(filter((file) => {
      if (included.indexOf(file.path) === -1) {
        return true;
      } else {
        return false;
      }
    }))
    .pipe(concat('report.custom.js'))
    .pipe(sourcemaps.init())
    .pipe(gulpUglify({
      mangle: false,
      compress: true
    }))
    .pipe(logger({after: 'source map complete!', extname: '.map', showChange: true}))
    .pipe(gulp.dest("./dist/js"));
});


2.
1. 准备环境
安装node+npm blog.csdn.net/antma/artic…
2. 文件规则
1. 文件命名:以report.开头
2. 文件内容:使用AMD规范
3. 目录创建: 保证文件与gulpfile文件同一路径
3. 使用规则
1.使用npm安装相关依赖
npm install
2. 启动node服务,输入指令 gulp custom -c xxx,yyyy, zzzz
gulp custom -c必须输入指令 xxx,yyy,zzz自己定义的模块

例:

 gulp custom -c animal,dog,cat 

3.后续使用出现的问题

就是在打包的时候出现了

Error: Received a non-Vinyl object in `dest()`

what这是什么玩意啊,lzzscl,google了一下只有github上的issue有说道可能是版本过低的问题,so找一下,康康

npm list vinyl-fs

然后找到一个版本2.0的,然后我就把它升级了,这个报错也就解决了