使用gulp打包传统项目
传统的开发项目,基于jquery和bootstrap框架做的开发
现在需要对项目做压缩处理,但是不能修改文件的相对位置
创建一个项目将项目源码放在src目录下,执行
npm init
新建一个gulpfile.js,这是gulp运行需要的文件,所有的gulp的任务都是在这个文件里执行的
安装gulp依赖(gulp和cli)
npm install gulp gulp-cli--save
分析:
1. 首先获取到src的所有源文件,将需要编译压缩的文件分类
js/css/image/html/others,其中的others不需要编译压缩,需要直接复制
2. 对每类文件做对应的任务
3. 执行任务(开始执行压缩任务之前,需要先清空dist“输出目录”)
- 首先获取到src的所有源文件,将需要编译压缩的文件分类
```javascript
const fs = require("fs");
const path = require("path");
const srcPath = path.resolve("./src");
const pluginPath = path.resolve("./src/javascript/plugin");
const getSrcFile = () => {
let fileClass = {
js: [],
css: [],
html: [],
image: [],
others: []
};
/**
* 获取所有文件的
* @param filePath 文件夹路径
* @param status 是否需要打包
*/
function getAllFile(filePath, status) {
let files = fs.readdirSync(filePath);
files.forEach(file => {
// 读取所有的文件夹
let fileDir = path.join(filePath, file);
let fileStat = fs.statSync(fileDir);
if (fileStat.isDirectory()) {
// 如果是文件夹 递归获取下面的文件
// plugin文件夹下不打包
if (fileDir === pluginPath) {
getAllFile(fileDir, false);
} else {
getAllFile(fileDir, status);
}
} else if (fileStat.isFile()) {
if (status) {
// 需要打包的
if (/\.js$/.test(file)) {
fileClass.js.push(fileDir);
} else if (/\.css$/.test(file)) {
fileClass.css.push(fileDir);
} else if (/\.html$/.test(file)) {
fileClass.html.push(fileDir);
} else if (/\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/.test(file)) {
fileClass.image.push(fileDir);
} else if (!/\.less$/.test(file)) {
// less文件不需要打包
fileClass.others.push(fileDir);
}
} else {
fileClass.others.push(fileDir);
}
}
});
}
getAllFile(srcPath, true);
return fileClass;
};
const {js, css, html, image, others} = getSrcFile();
```
- 对每类文件做对应的任务
const distPath = path.resolve("./dist");
const gulp = require("gulp");
const uglify = require("gulp-uglify");
const babel = require('gulp-babel');
const minifyCSS = require('gulp-minify-css');
const imagemin = require('gulp-imagemin');
const htmlmin = require('gulp-htmlmin');
/**
* 获取文件输出路径
* @param filePath
* @returns {string}
*/
const getOutputPath = (filePath) => {
let destPath = filePath.replace(srcPath, distPath