使用gulp打包传统项目

使用gulp打包传统项目

传统的开发项目,基于jquerybootstrap框架做的开发

现在需要对项目做压缩处理,但是不能修改文件的相对位置

创建一个项目将项目源码放在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“输出目录”)

  1. 首先获取到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();
```
  1. 对每类文件做对应的任务
	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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值