导航菜单

  • 0.api
  • 0.Async
  • 0.module
  • 1.ES2015
  • 2.Promise
  • 3.Node
  • 4.NodeInstall
  • 5.REPL
  • 6.NodeCore
  • 7.module&NPM
  • 8.Encoding
  • 9.Buffer
  • 10.fs
  • 11.Stream-1
  • 11.Stream-2
  • 11.Stream-3
  • 11.Stream-4
  • 12-Network-2
  • 12.NetWork-3
  • 12.Network-1
  • 13.tcp
  • 14.http-1
  • 14.http-2
  • 15.compress
  • 16.crypto
  • 17.process
  • 18.yargs
  • 19.cache
  • 20.action
  • 21.https
  • 22.cookie
  • 23.session
  • 24.express-1
  • 24.express-2
  • 24.express-3
  • 24.express-4
  • 25.koa-1
  • 26.webpack-1-basic
  • 26.webpack-2-optimize
  • 26.webpack-3-file
  • 26.webpack-4.tapable
  • 26.webpack-5-AST
  • 26.webpack-6-sources
  • 26.webpack-7-loader
  • 26.webpack-8-plugin
  • 26.webpack-9-hand
  • 26.webpack-10-prepare
  • 28.redux
  • 28.redux-jwt-back
  • 28.redux-jwt-front
  • 29.mongodb-1
  • 29.mongodb-2
  • 29.mongodb-3
  • 29.mongodb-4
  • 29.mongodb-5
  • 29.mongodb-6
  • 30.cms-1-mysql
  • 30.cms-2-mysql
  • 30.cms-3-mysql
  • 30.cms-4-nunjucks
  • 30.cms-5-mock
  • 30.cms-6-egg
  • 30.cms-7-api
  • 30.cms-8-roadhog
  • 30.cms-9-yaml
  • 30.cms-10-umi
  • 30.cms-12-dva
  • 30.cms-13-dva-ant
  • 30.cms-14-front
  • 30.cms-15-deploy
  • 31.dva
  • 31.cms-13-dva-antdesign
  • 33.redis
  • 34.unittest
  • 35.jwt
  • 36.websocket-1
  • 36.websocket-2
  • 38.chat-api-1
  • 38.chat-api-2
  • 38.chat-3
  • 38.chat-api-3
  • 38.chat
  • 38.chat2
  • 38.chat2
  • 39.crawl-0
  • 39.crawl-1
  • 39.crawl-2
  • 40.deploy
  • 41.safe
  • 42.test
  • 43.nginx
  • 44.enzyme
  • 45.docker
  • 46.elastic
  • 47.oauth
  • 48.wxpay
  • index
  • 52.UML
  • 53.design
  • index
  • 54.linux
  • 57.ts
  • 56.react-ssr
  • 58.ts_react
  • 59.ketang
  • 59.ketang2
  • 61.1.devops-linux
  • 61.2.devops-vi
  • 61.3.devops-user
  • 61.4.devops-auth
  • 61.5.devops-shell
  • 61.6.devops-install
  • 61.7.devops-system
  • 61.8.devops-service
  • 61.9.devops-network
  • 61.10.devops-nginx
  • 61.11.devops-docker
  • 61.12.devops-jekins
  • 61.13.devops-groovy
  • 61.14.devops-php
  • 61.15.devops-java
  • 61.16.devops-node
  • 61.17.devops-k8s
  • 62.1.react-basic
  • 62.2.react-state
  • 62.3.react-high
  • 62.4.react-optimize
  • 62.5.react-hooks
  • 62.6.react-immutable
  • 62.7.react-mobx
  • 62.8.react-source
  • 63.1.redux
  • 63.2.redux-middleware
  • 63.3.redux-hooks
  • 63.4.redux-saga
  • 63.5.redux-saga-hand
  • 64.1.router
  • 64.2.router-connected
  • 65.1.typescript
  • 65.2.typescript
  • 65.3.typescript
  • 65.4.antd
  • 65.4.definition
  • 66-1.vue-base
  • 66-2.vue-component
  • 66-3.vue-cli3.0
  • 66-4.$message组件
  • 66-5.Form组件
  • 66-6.tree
  • 66-7.vue-router-apply
  • 66-8.axios-apply
  • 66-9.vuex-apply
  • 66-10.jwt-vue
  • 66-11.vue-ssr
  • 66-12.nuxt-apply
  • 66-13.pwa
  • 66-14.vue单元测试
  • 66-15.权限校验
  • 67-1-network
  • 68-2-wireshark
  • 7.npm2
  • 69-hooks
  • 70-deploy
  • 71-hmr
  • 72.deploy
  • 73.import
  • 74.mobile
  • 75.webpack-1.文件分析
  • 75.webpack-2.loader
  • 75.webpack-3.源码流程
  • 75.webpack-4.tapable
  • 75.webpack-5.prepare
  • 75.webpack-6.resolve
  • 75.webpack-7.loader
  • 75.webpack-8.module
  • 75.webpack-9.chunk
  • 75.webpack-10.asset
  • 75.webpack-11.实现
  • 76.react_optimize
  • 77.ts_ketang_back
  • 77.ts_ketang_front
  • 78.vue-domdiff
  • 79.grammar
  • 80.tree
  • 81.axios
  • 82.1.react
  • 82.2.react-high
  • 82.3.react-router
  • 82.4.redux
  • 82.5.redux_middleware
  • 82.6.connected
  • 82.7.saga
  • 82.8.dva
  • 82.8.dva-source
  • 82.9.roadhog
  • 82.10.umi
  • 82.11.antdesign
  • 82.12.ketang-front
  • 82.12.ketang-back
  • 83.upload
  • 84.graphql
  • 85.antpro
  • 86.1.uml
  • 86.2.design
  • 87.postcss
  • 88.react16-1
  • 89.nextjs
  • 90.react-test
  • 91.react-ts
  • 92.rbac
  • 93.tsnode
  • 94.1.JavaScript
  • 94.2.JavaScript
  • 94.3.MODULE
  • 94.4.EventLoop
  • 94.5.文件上传
  • 94.6.https
  • 94.7. nginx
  • 95.1. react
  • 95.2.react
  • 96.1.react16
  • 96.2.fiber
  • 96.3.fiber
  • 97.serverless
  • 98.websocket
  • 100.1.react-basic
  • 101.1.monitor
  • 101.2.monitor
  • 102.java
  • 103.1.webpack-usage
  • 103.2.webpack-bundle
  • 103.3.webpack-ast
  • 103.4.webpack-flow
  • 103.5.webpack-loader
  • 103.6.webpack-tapable
  • 103.7.webpack-plugin
  • 103.8.webpack-optimize1
  • 103.9.webpack-optimize2
  • 103.10.webpack-hand
  • 103.11.webpack-hmr
  • 103.11.webpack5
  • 103.13.splitChunks
  • 103.14.webpack-sourcemap
  • 103.15.webpack-compiler1
  • 103.15.webpack-compiler2
  • 103.16.rollup.1
  • 103.16.rollup.2
  • 103.16.rollup.3
  • 103.16.vite.basic
  • 103.16.vite.source
  • 103.16.vite.plugin
  • 103.16.vite.1
  • 103.16.vite.2
  • 103.17.polyfill
  • 104.1.binary
  • 104.2.binary
  • 105.skeleton
  • 106.1.react
  • 106.2.react_hooks
  • 106.3.react_router
  • 106.4.redux
  • 106.5.redux_middleware
  • 106.6.connected-react-router
  • 106.6.redux-first-history
  • 106.7.redux-saga
  • 106.8.dva
  • 106.9.umi
  • 106.10.ketang
  • 106.11.antdesign
  • 106.12.antpro
  • 106.13.router-6
  • 106.14.ssr
  • 106.15.nextjs
  • 106.16.1.cms
  • 106.16.2.cms
  • 106.16.3.cms
  • 106.16.4.cms
  • 106.16.mobx
  • 106.17.fomily
  • 107.fiber
  • 108.http
  • 109.1.webpack_usage
  • 109.2.webpack_source
  • 109.3.dll
  • 110.nest.js
  • 111.xstate
  • 112.Form
  • 113.redux-saga
  • 114.react+typescript
  • 115.immer
  • 116.pro5
  • 117.css-loader
  • 118.1.umi-core
  • 119.2.module-federation
  • 119.1.module-federation
  • 120.create-react-app
  • 121.react-scripts
  • 122.react-optimize
  • 123.jsx-runtime
  • 124.next.js
  • 125.1.linux
  • 125.2.linux-vi
  • 125.3.linux-user
  • 125.4.linux-auth
  • 125.5.linux-shell
  • 125.6.linux-install
  • 125.7.linux-system
  • 125.8.linux-service
  • 125.9.linux-network
  • 125.10.nginx
  • 125.11.docker
  • 125.12.ci
  • 125.13.k8s
  • 125.14.k8s
  • 125.15.k8s
  • 125.16.k8s
  • 126.11.react-1
  • 126.12.react-2
  • 126.12.react-3
  • 126.12.react-4
  • 126.12.react-5
  • 126.12.react-6
  • 126.12.react-7
  • 126.12.react-8
  • 127.frontend
  • 128.rollup
  • 129.px2rem-loader
  • 130.health
  • 131.hooks
  • 132.keepalive
  • 133.vue-cli
  • 134.react18
  • 134.2.react18
  • 134.3.react18
  • 135.function
  • 136.toolkit
  • 137.lerna
  • 138.create-vite
  • 139.cli
  • 140.antd
  • 141.react-dnd
  • 142.1.link
  • 143.1.gulp
  • 143.2.stream
  • 143.3.gulp
  • 144.1.closure
  • 144.2.v8
  • 144.3.gc
  • 145.react-router-v6
  • 146.browser
  • 147.lighthouse
  • 148.1.basic
  • 148.2.basic
  • 148.3.basic
  • 148.4.basic
  • 148.5.basic
  • 149.1.vite
  • 149.2.vite
  • 149.3.vite
  • 149.4.vite
  • 150.react-window
  • 151.react-query
  • 152.useRequest
  • 153.transition
  • 154.emotion
  • 155.1.formily
  • 155.2.formily
  • 155.3.formily
  • 155.3.1.mobx.usage
  • 155.3.2.mobx.source
  • 156.vue-loader
  • 103.11.mf
  • 157.1.react18
  • 158.umi4
  • 159.rxjs
  • 159.rxjs2
  • 160.bff
  • 161.zustand
  • 162.vscode
  • 163.emp
  • 164.cors
  • 1.什么是gulp
  • 2. gulp特点
  • 3. 安装gulp
  • 4. 异步任务和组合任务
  • 5. gulp核心API
    • 5.1 gulp.src()
    • 5.2 gulp.dest()
    • 5.3 pipe
  • 6. gulp实战
    • 6.1 安装
    • 6.2 编译样式
    • 6.3 编译脚本
    • 6.4 编译html
      • 6.4.1 src\index.html
      • 6.4.2 circle.svg
      • 6.4.3 static\rect.svg
      • 6.4.4 gulpfile.js
    • 6.5 编译任务
    • 6.6 压缩图片
      • 6.6.1 安装
      • 6.6.2 gulpfile.js
    • 6.7 拷贝静态文件
    • 6.8 删除输出目录
    • 6.9 自动加载插件
    • 6.10 开发服务器
      • 6.10.1 gulpfile.js
      • 6.10.2 main.js
    • 6.11 监听文件变化
      • 6.11.1 gulpfile.js
    • 6.12. 合并和压缩
      • 6.12.1 src\index.html
      • 6.12.2 gulpfile.js
  • 7. 参考知识
    • 7.1 glob
      • 7.1.1 glob规则
      • 7.1.2 glob示例

1.什么是gulp #

  • gulp是可以自动化执行任务的工具 在平时开发的流程里面,一定有一些任务需要手工重复得执行,比如:
    • 把文件从开发目录拷贝到生产目录
    • 把多个 JS 或者 CSS 文件合并成一个文件
    • 对JS文件和CSS进行压缩
    • 把sass或者less文件编译成CSS
    • 压缩图像文件
    • 创建一个可以实时刷新页面内容的本地服务器

      只要你觉得有些动作是要重复去做的,就可以把这些动作创建成一个gulp任务,然后在指定的条件下自动执行

2. gulp特点 #

  • 易于使用 通过代码优于配置的策略,Gulp 让简单的任务简单,复杂的任务可管理
  • 快速构建 利用 node.js 流的威力,你可以快速构建项目并减少频繁的 IO 操作
  • 高质量的插件 Gulp 严格的插件指南确保插件如你期望的那样简洁地工作
  • 易于学习 通过最少的 API,掌握 gulp 毫不费力,构建工作尽在掌握

3. 安装gulp #

  • quick-start
npm install --g gulp-cli
npm install --save-dev gulp

4. 异步任务和组合任务 #

gulpfile.js

const fs = require('fs');
const through = require('through2');
const { series, parallel } = require('gulp');
function callbackTask(done) {
    setTimeout(() => {
        console.log('callbackTask');
        done();
    }, 1000);
}
function promiseTask() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('promiseTask');
            resolve();
        }, 1000);
    });
}
async function asyncTask() {
    await new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
    console.log('asyncTask');
}
function streamTask() {
    return fs.createReadStream('input.txt')
        .pipe(through((chunk, encoding, next) => {
            setTimeout(() => {
                next(null, chunk);
            }, 1000);
        }))
        .pipe(fs.createWriteStream('output.txt'))
}

const parallelTask = parallel(callbackTask, promiseTask, asyncTask, streamTask);
const seriesTask = series(callbackTask, promiseTask, asyncTask, streamTask);
exports.callback = callbackTask
exports.promise = promiseTask
exports.async = asyncTask
exports.stream = streamTask
exports.parallel = parallelTask
exports.series = seriesTask

5. gulp核心API #

5.1 gulp.src() #

  • gulp.src()方法正是用来获取流的
  • 注意这个流里的内容不是原始的文件流,而是一个虚拟文件对象流
  • globs 参数是文件匹配模式(类似正则表达式),用来匹配文件路径(包括文件名),当然这里也可以直接指定某个具体的文件路径。当有多个匹配模式时,该参数可以为一个数组
  • options 为可选参数
gulp.src(globs[, options])

5.2 gulp.dest() #

  • gulp.dest()是用来向硬盘写入文件的
    • path 为写入文件的路径
    • options 为一个可选的参数对象
  • gulp.dest()传入的路径参数只能用来指定要生成的文件的目录,而不能指定生成文件的文件名 它生成文件的文件名使用的是导入到它的文件流自身的文件名 所以生成的文件名是由导入到它的文件流决定的
  • gulp.dest(path)生成的文件路径是我们传入的path参数后面再加上gulp.src()中有通配符开始出现的那部分路径
  • 通过指定gulp.src()方法配置参数中的base属性,我们可以更灵活的来改变gulp.dest()生成的文件路径
gulp.dest(path[,options])

5.3 pipe #

gulpfile.js

const { src, dest } = require('gulp');
function copyTask() {
    console.log('执行拷贝任务');
    return src('src/**/*.js').pipe(dest('dist'));
}
exports.default = copyTask;

6. gulp实战 #

6.1 安装 #

cnpm install @babel/core @babel/preset-env browser-sync gulp gulp-babel gulp-clean gulp-clean-css gulp-ejs gulp-htmlmin gulp-if gulp-imagemin gulp-less gulp-load-plugins gulp-uglify gulp-useref gulp-watch map-stream bootstrap jquery --save

6.2 编译样式 #

const { src, dest } = require('gulp');
const less = require('gulp-less');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

exports.styles = styles;

6.3 编译脚本 #

const { src, dest } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

+const scripts = () => {
+    return src("src/scripts/*.js", { base: 'src' })
+        .pipe(babel({
+            presets: ["@babel/preset-env"]
+        }))
+        .pipe(dest('dist'))
+}

exports.styles = styles;
+exports.scripts = scripts;

6.4 编译html #

6.4.1 src\index.html #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%=title%></title>
        <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="styles/main.css"/>
</head>
<body>
    <button class="btn btn-danger">按钮</button>
    <img src="assets/images/circle.svg"/>
    <img src="rect.svg"/>
    <script src="node_modules/jquery/dist/jquery.js"></script>
    <script src="scripts/main.js"></script>
</body>
</html>

6.4.2 circle.svg #

src\assets\images\circle.svg

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100" height="100" version="1.1" xmlns="http://www.w3.org/2000/svg">
 <circle cx="50" cy="50" r="50"  fill="red"/>
</svg>

6.4.3 static\rect.svg #

static\rect.svg

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100" height="100" version="1.1" xmlns="http://www.w3.org/2000/svg">
 <rect  width="100" height="100" style="fill:red;"/>
</svg>

6.4.4 gulpfile.js #

const { src, dest, parallel } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const ejs = require('gulp-ejs');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

+const html = () => {
+    return src("src/*.html", { base: 'src' })
+        .pipe(ejs({ title: 'gulp' }))
+        .pipe(dest('dist'))
+}
exports.styles = styles;
exports.scripts = scripts;
+exports.html = html;

6.5 编译任务 #

const { src, dest, parallel } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const ejs = require('gulp-ejs');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}
+const compile = parallel(styles, scripts, html);
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
+exports.compile = compile;

6.6 压缩图片 #

6.6.1 安装 #

npm install gulp-imagemin --save-dev
npm install imagemin-jpegtran imagemin-svgo imagemin-gifsicle imagemin-optipng --save-dev

6.6.2 gulpfile.js #

const { src, dest, parallel } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const ejs = require('gulp-ejs');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}

+const images = async () => {
+    let imagemin = await import('gulp-imagemin');
+    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
+        .pipe(imagemin.default())
+        .pipe(dest('dist'))
+}

const compile = parallel(styles, scripts, html);
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
+exports.images = images;

6.7 拷贝静态文件 #

const { src, dest, parallel } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const ejs = require('gulp-ejs');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}

const images = async () => {
    let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

+const static = async () => {
+    return src("static/**", { base: 'static' })
+        .pipe(dest('dist'))
+}

const compile = parallel(styles, scripts, html);
+const build = parallel(compile, static)
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
exports.images = images;
+exports.static = static;
+exports.build = build;

6.8 删除输出目录 #

const { src, dest, parallel, series } = require('gulp');
const less = require('gulp-less');
const babel = require('gulp-babel');
const ejs = require('gulp-ejs');
+const gulpClean = require('gulp-clean');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}

const images = async () => {
    let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

const static = async () => {
    return src("static/**", { base: 'static' })
        .pipe(dest('dist'))
}
+const clean =  () => {
+    return src("dist/**", { read: false })
+        .pipe(gulpClean())
+}
const compile = parallel(styles, scripts, html);
+const build = series(clean, parallel(compile, static));
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
exports.images = images;
exports.static = static;
exports.build = build;
+exports.clean = clean;

6.9 自动加载插件 #

const { src, dest, parallel, series } = require('gulp');
-const less = require('gulp-less');
-const babel = require('gulp-babel');
-const ejs = require('gulp-ejs');
-const gulpClean = require('gulp-clean');
+const plugins = require('gulp-load-plugins')();
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
+       .pipe(plugins.less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
+       .pipe(plugins.babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
+       .pipe(plugins.ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}

const images = async () => {
     let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

const static = async () => {
    return src("static/**", { base: 'static' })
        .pipe(dest('dist'))
}
const clean =  () => {
    return src("dist/**", { read: false })
+       .pipe(plugins.clean())
}
const compile = parallel(styles, scripts, html);
const build = series(clean, parallel(compile, static));
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
exports.images = images;
exports.static = static;
exports.build = build;
exports.clean = clean;

6.10 开发服务器 #

6.10.1 gulpfile.js #

const { src, dest, parallel, series } = require('gulp');
const plugins = require('gulp-load-plugins')();
+const browserSync = require('browser-sync');
+const path = require('path');
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(plugins.less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(plugins.babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(plugins.ejs({ title: 'gulp' }))
        .pipe(dest('dist'))
}

const images = async () => {
    let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

const static = async () => {
    return src("static/**", { base: 'static' })
        .pipe(dest('dist'))
}
const clean = () => {
    return src("dist/**", { read: false })
        .pipe(plugins.clean())
}
+const serve = () => {
+    return browserSync.create().init({
+        notify: false,
+        server: {
+            baseDir: 'dist',
+            routes: {
+                '/node_modules': path.resolve('node_modules')
+            }
+        }
+    });
+}
const compile = parallel(styles, scripts, html);
const build = series(clean, parallel(compile, static));
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
exports.images = images;
exports.static = static;
exports.build = build;
exports.clean = clean;
+exports.serve = serve;

6.10.2 main.js #

src\scripts\main.js

let sum = (a, b) => a + b;
sum(1, 3)
+$(() => {
+    console.log('jquery');
+});

6.11 监听文件变化 #

6.11.1 gulpfile.js #

const { src, dest, parallel, series, watch } = require('gulp');
const plugins = require('gulp-load-plugins')();
const browserSync = require('browser-sync');
const path = require('path');
+const browserServer = browserSync.create();
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(plugins.less())
        .pipe(dest('dist'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(plugins.babel({
            presets: ["@babel/preset-env"]
        }))
        .pipe(dest('dist'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
+       .pipe(plugins.ejs({ title: 'gulp' }, { cache: false }))
        .pipe(dest('dist'))
}

const images = async () => {
    let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

const static = async () => {
    return src("static/**", { base: 'static' })
        .pipe(dest('dist'))
}
const clean = () => {
    return src("dist/**", { read: false })
        .pipe(plugins.clean())
}
const serve = () => {
+   watch("src/styles/*.less", styles);
+   watch("src/scripts/*.js", scripts);
+   watch("src/*.html", html);
+   watch([
+       "src/assets/images/**/*.@(jpg|png|gif|svg)",
+       "static/**"
+   ], browserServer.reload);
    return browserServer.init({
        notify: false,
+       files: ['dist/**'],
        server: {
+           baseDir: ['dist', 'src', 'static'],
            routes: {
                '/node_modules': path.resolve('node_modules')
            }
        }
    });
}
const compile = parallel(styles, scripts, html);
+const build = series(clean, parallel(compile, images, static));
+const dev = series(clean, compile, serve);
exports.styles = styles;
exports.scripts = scripts;
exports.html = html;
exports.compile = compile;
exports.images = images;
exports.static = static;
exports.clean = clean;
exports.serve = serve;
+exports.build = build;
+exports.dev = dev;

6.12. 合并和压缩 #

6.12.1 src\index.html #

src\index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%=title%></title>
+   <!-- build:css styles/dist.css  -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="styles/main.css"/>
+   <!-- endbuild -->
</head>
<body>
    <button class="btn btn-danger">按钮</button>
    <img src="assets/images/circle.svg"/>
    <img src="rect.svg"/>
+   <!-- build:js scripts/dist.js  -->
    <script src="node_modules/jquery/dist/jquery.js"></script>
    <script src="scripts/main.js"></script>
+   <!-- endbuild -->
</body>
</html>

6.12.2 gulpfile.js #

const { src, dest, parallel, series, watch } = require('gulp');
const plugins = require('gulp-load-plugins')();
const browserSync = require('browser-sync');
const path = require('path');
const browserServer = browserSync.create();
const styles = () => {
    return src("src/styles/*.less", { base: 'src' })
        .pipe(plugins.less())
+       .pipe(dest('temp'))
}

const scripts = () => {
    return src("src/scripts/*.js", { base: 'src' })
        .pipe(plugins.babel({
            presets: ["@babel/preset-env"]
        }))
+       .pipe(dest('temp'))
}

const html = () => {
    return src("src/*.html", { base: 'src' })
        .pipe(plugins.ejs({ title: 'gulp' }, { cache: false }))
+       .pipe(dest('temp'))
}

const images = async () => {
    let imagemin = await import('gulp-imagemin');
    return src("src/assets/images/**/*.@(jpg|png|gif|svg)", { base: 'src' })
        .pipe(imagemin.default())
        .pipe(dest('dist'))
}

const static = async () => {
    return src("static/**", { base: 'static' })
        .pipe(dest('dist'))
}
const clean = () => {
+   return src(["dist/**", "temp/**"], { read: false })
+       .pipe(plugins.clean({ allowEmpty: true }));
}
const serve = () => {
    watch("src/styles/*.less", styles);
    watch("src/scripts/*.js", scripts);
    watch("src/*.html", html);
    watch([
        "src/assets/images/**/*.@(jpg|png|gif|svg)",
        "static/**"
    ], browserServer.reload);
    return browserServer.init({
        notify: false,
        files: ['dist/**'],
        server: {
+           baseDir: ['temp', 'src', 'static'],
            routes: {
                '/node_modules': path.resolve('node_modules')
            }
        }
    });
}

+const concat = () => {
+    return src('temp/*.html', { base: 'temp' })
+        .pipe(plugins.useref({
+            searchPath: ['temp', '.']
+        }))
+        .pipe(plugins.if('*.html', plugins.htmlmin({
+            collapseWhitespace: true,
+            minifyCSS: true,
+            minifyJS: true
+        })))
+        .pipe(plugins.if('*.js', plugins.uglify()))
+        .pipe(plugins.if('*.css', plugins.cleanCss()))
+        .pipe(dest('dist'));
+}

const compile = parallel(styles, scripts, html);
+const build = series(clean, parallel(series(compile, concat), images, static));
const dev = series(clean, compile, serve);
-exports.styles = styles;
-exports.scripts = scripts;
-exports.html = html;
-exports.compile = compile;
-exports.images = images;
-exports.static = static;
-exports.serve = serve;
-exports.concat = concat;
-exports.clean = clean;
-exports.build = build;
-exports.dev = dev;

+module.exports = {
+    clean,
+    build,
+    dev
+}

7. 参考知识 #

7.1 glob #

  • gulp内部使用了node-glob模块来实现其文件匹配功能

7.1.1 glob规则 #

匹配符 说明
* 匹配文件路径中的0个或多个字符,但不会匹配路径分隔符
** 匹配路径中的0个或多个目录及其子目录
? 匹配文件路径中的一个字符(不会匹配路径分隔符)
[...] 匹配方括号中出现的字符中的任意一个,当方括号中第一个字符为^或!时,则表示不匹配方括号中出现的其他字符中的任意一个
!(pattern1 pattern2 pattern3) 匹配任何与括号中给定的任一模式都不匹配的
?(pattern1 pattern2 pattern3) 匹配括号中给定的任一模式0次或1次,类似于js正则中的(pattern1 pattern2 pattern3)?
+(pattern1 patter2n pattern3) 匹配括号中给定的任一模式至少1次,类似于js正则中的(pattern1 pattern2 pattern3)+
(pattern1 pattern2 pattern3) 匹配括号中给定的任一模式0次或多次,类似于js正则中的(pattern1 pattern2 pattern3)*
@(pattern1 pattern2 pattern3) 匹配括号中给定的任一模式1次,类似于js正则中的(pattern1 pattern2 pattern3)

7.1.2 glob示例 #

glob 匹配
* 能匹配 a.js,x.y,abc,abc/,但不能匹配a/b.js
. a.js,style.css,a.b,x.y
//*.js 能匹配 a/b/c.js,x/y/z.js,不能匹配a/b.js,a/b/c/d.js
** 能匹配 abc,a/b.js,a/b/c.js,x/y/z,x/y/z/a.b,能用来匹配所有的目录和文件
a/**/z 能匹配 a/z,a/b/z,a/b/c/z,a/d/g/h/j/k/z
a/**b/z 能匹配 a/b/z,a/sb/z,但不能匹配a/x/sb/z,因为只有单**单独出现才能匹配多级目录
?.js 能匹配 a.js,b.js,c.js
a?? 能匹配 a.b,abc,但不能匹配ab/,因为它不会匹配路径分隔符
[xyz].js 只能匹配 x.js,y.js,z.js,不会匹配xy.js,xyz.js等,整个中括号只代表一个字符
[^xyz].js 能匹配 a.js,b.js,c.js等,不能匹配x.js,y.js,z.js

访问验证

请输入访问令牌

Token不正确,请重新输入