gulp(自动化构建工具)实现过程总结

it2022-05-05  176

1.copy

创建package.json

nodejs项目的配置文件

{ "name": "gulp_study", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.4.5", "@babel/preset-env": "^7.4.5", "browser-sync": "^2.26.5", "gulp": "^4.0.2", "gulp-babel": "^8.0.0", "gulp-browsersync-inject": "^1.0.1", "gulp-cssmin": "^0.2.0", "gulp-imagemin": "^5.0.3", "gulp-sass": "^4.0.2", "gulp-uglify": "^3.0.2" }, "dependencies": { "gulp-htmlmin": "^5.0.1" } }

创建gulpfile.js

gulp的配置文件

const gulp = require("gulp"); // 将scss文件转css const sass = require("gulp-sass"); // 将es6转es5 const babel = require("gulp-babel"); //丑化js const uglify = require('gulp-uglify'); //图片压缩 const imagemin = require("gulp-imagemin"); // 压缩html const htmlmin = require('gulp-htmlmin'); //浏览器同步测试工具browserSync var browserSync = require('browser-sync').create(); var reload = browserSync.reload; function trans_sass(){ return gulp.src("src/sass/*.scss") .pipe(sass({ outputStyle:"compressed" })) .pipe(gulp.dest("dest/css")) .pipe(reload({stream: true})); } function trans_es6(){ return gulp.src("src/js/*.js") .pipe(babel({ presets: ['@babel/env'] })) .pipe(uglify()) .pipe(gulp.dest("dest/js")) .pipe(reload({stream: true})) } function imgin(){ return gulp.src("src/imgs/*") .pipe(imagemin([ imagemin.gifsicle({interlaced: true}), imagemin.jpegtran({progressive: true}), imagemin.optipng({optimizationLevel: 5}), imagemin.svgo({ plugins: [ {removeViewBox: true}, {cleanupIDs: false} ] }) ])) .pipe(gulp.dest("dest/imgs")) .pipe(reload({stream: true})) } function htmlm(){ return gulp.src("./*.html") .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest("dest")) .pipe(reload({stream: true})) } gulp.task("sass",trans_sass); gulp.task("es6",trans_es6); gulp.task("imgmin",imgin); gulp.task("htmlmin",htmlm); //监听文件的改动,后做出相应的操作 function watch(){ // 初始化browser-sync的服务器 browserSync.init({ server: { baseDir: "./dest", index:"index.html" }, port: 8080 }); gulp.watch("./src/js/*.js",trans_es6); gulp.watch("./src/sass/*.scss",trans_sass); gulp.watch("./src/imgs/*",imgin); gulp.watch("./*.html",htmlm); } gulp.task("default",gulp.series(trans_sass,trans_es6,imgin,htmlm,watch))

2.在新的目录里边运行 npm install 如果安装不成功,需要配置淘宝镜像

npm install -g cnpm --registry=https://registry.npm.taobao.org

这样cnpm 命令相当于npm命令,

执行cnpm install,在package.json中依赖的包都会自动安装

3.只要不改变目录结构,gulpfile文件不用修改

4.运行gulp命令

前提是全局安装gulp

cnpm install gulp -g

5.自动会启动一个服务器,可以配置端口号

6.可以在目录里边写sass,es6,会自动的转换成es5和css,

7.项目完成后,打包上线的文件夹是dest


最新回复(0)