search
HomeWeb Front-endJS TutorialGulp practical configuration (2) - small and medium-sized projects

The gulp configuration in the previous article is very simple, mainly for demo viewing and debugging. This article will be relatively detailed, including compression, merging, and timestamps.

In cities with relatively good Internet environments, larger projects that require multi-person collaboration should all use modularity (here mainly refers to commonjs and ES6 module systems, not the earlier require.js and sea.js) . The code will also focus more on how to separate and inject, rather than simply merging.

But in many small companies, the development models or technologies are still relatively traditional, or some small projects do not need to use the more cutting-edge technologies at all.

So this configuration is mainly for such small and medium-sized projects.

1. Required tools and versions

Package management tool: yarn v0.24.5

Automated build tool: gulp v4.0

2.Tool installation

yarn add global gulpjs/gulp#4.0

3. Development environment configuration

<span style="color: #0000ff">var</span> gulp = require('gulp'<span style="color: #000000">),
    pug </span>= require('gulp-pug'<span style="color: #000000">),
    less </span>= require('gulp-less'<span style="color: #000000">),
    </span><span style="color: #008000">//</span><span style="color: #008000">当发生异常时提示错误 确保本地安装gulp-notify和gulp-plumber</span>
    notify = require('gulp-notify'<span style="color: #000000">),
    plumber </span>= require('gulp-plumber'<span style="color: #000000">),
    sourcemaps </span>= require('gulp-sourcemaps'<span style="color: #000000">),
    browserSync </span>= require('browser-sync'<span style="color: #000000">).create()
    reload </span>=<span style="color: #000000"> browserSync.reload;

</span><span style="color: #0000ff">var</span> LessAutoprefix = require('less-plugin-autoprefix'<span style="color: #000000">),
    autoprefix </span>= <span style="color: #0000ff">new</span> LessAutoprefix({ browsers: ['last 2 versions'<span style="color: #000000">] });

</span><span style="color: #008000">//</span><span style="color: #008000"> 文件路径</span>
<span style="color: #0000ff">var</span> paths =<span style="color: #000000"> {
  pug: {
    src: </span>'src/pug/pages/*.pug'<span style="color: #000000">,
    dest: </span>'dev/html/'<span style="color: #000000">,
    watch: </span>'src/pug/**/*.pug'<span style="color: #000000">
  },
  less: {
    src: </span>'src/less/**/*.less'<span style="color: #000000">,
    dest: </span>'dev/css/'<span style="color: #000000">,
    watch: </span>'src/less/**/*.less'<span style="color: #000000">
  },
  js: {
    src: </span>'src/js/**/*.js'<span style="color: #000000">,
    dest: </span>'dev/js/'<span style="color: #000000">,
    watch: </span>'src/js/**/*.js'<span style="color: #000000">
  },
  img: {
    src: </span>'src/img/**/*'<span style="color: #000000">,
    dest: </span>'dev/img/'<span style="color: #000000">,
    watch: </span>'src/img/**/*'<span style="color: #000000">
  }
}

</span><span style="color: #008000">//</span><span style="color: #008000"> 启动 browserSync 服务,自己启动server,并且为浏览器实时刷新提供服务</span>
gulp.task('browserSync', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> browserSync.init({
    server: {
      baseDir: </span>'./'<span style="color: #000000">
    },
    files: </span>'./dev/**/*'<span style="color: #000000">
  });
})

</span><span style="color: #008000">//</span><span style="color: #008000"> 将pug文件转换为html</span>
gulp.task('pug', <span style="color: #0000ff">function</span><span style="color: #000000"> buildHTML() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.pug.src)
    .pipe(plumber({errorHandler: notify.onError(</span>'Error: '<span style="color: #000000">)}))
    .pipe(pug())
    .pipe(gulp.dest(paths.pug.dest));
});

</span><span style="color: #008000">//</span><span style="color: #008000"> 编译less文件</span>
gulp.task('less', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.less.src)
    .pipe(plumber({errorHandler: notify.onError(</span>'Error: '<span style="color: #000000">)}))
    .pipe(sourcemaps.init())
    .pipe(less({
      plugins: [autoprefix]
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.less.dest));
})

</span><span style="color: #008000">//</span><span style="color: #008000"> 复制js文件</span>
gulp.task('js', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.js.src)
    .pipe(gulp.dest(paths.js.dest));
})

</span><span style="color: #008000">//</span><span style="color: #008000"> 复制img文件</span>
gulp.task('img', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.img.src)
    .pipe(gulp.dest(paths.img.dest));
})


</span><span style="color: #008000">//</span><span style="color: #008000"> 监听文件变化</span>
gulp.task('watch', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  gulp.watch(paths.pug.watch, gulp.parallel(</span>'pug'<span style="color: #000000">))
  gulp.watch(paths.less.watch, gulp.parallel(</span>'less'<span style="color: #000000">))
  gulp.watch(paths.js.watch, gulp.parallel(</span>'js'<span style="color: #000000">))
  gulp.watch(paths.img.watch, gulp.parallel(</span>'img'<span style="color: #000000">))
})

</span><span style="color: #008000">//</span><span style="color: #008000"> 默认任务,在命令行输入`gulp`来启动任务</span>
gulp.task('default', gulp.parallel('watch', 'browserSync', 'pug', 'less', 'js'))

gulp-pug This plug-in is used to compile pug templates, which are the previous jade templates. The pug template is a very powerful front-end and universal template engine, and it is also very simple to learn. For specific usage, please see my other article A tutorial article about pug - Blog system based on express+mongodb+pug - pug article.

Everyone knows that when gulp is monitoring tasks, if an error occurs in some link, gulp will be interrupted, and then the gulp task will have to be restarted. This is a very troublesome thing. . Here you can use two plug-ins, gulp-notify and gulp-plumber, to avoid gulp task interruption.

4. Production environment configuration

<span style="color: #0000ff">var</span> gulp = require('gulp'<span style="color: #000000">),
  del </span>= require('del'<span style="color: #000000">),
  pug </span>= require('gulp-pug'<span style="color: #000000">),
  less </span>= require('gulp-less'<span style="color: #000000">),
  cleanCSS </span>= require('gulp-clean-css'<span style="color: #000000">),
  base64 </span>= require('gulp-tobase64'<span style="color: #000000">),
  </span><span style="color: #008000">//</span><span style="color: #008000"> img64 = require('gulp-imgbase64'),</span>
  imagemin = require('gulp-imagemin'<span style="color: #000000">),
  babel </span>= require('gulp-babel'<span style="color: #000000">),
  uglify </span>= require('gulp-uglify'<span style="color: #000000">),
  rev </span>= require('gulp-rev'), <span style="color: #008000">//</span><span style="color: #008000"> 添加时间戳</span>
  revCollector = require('gulp-rev-collector'<span style="color: #000000">);


</span><span style="color: #0000ff">var</span> LessAutoprefix = require('less-plugin-autoprefix'<span style="color: #000000">),
  autoprefix </span>= <span style="color: #0000ff">new</span><span style="color: #000000"> LessAutoprefix({
    browsers: [</span>'last 2 versions'<span style="color: #000000">]
  });

</span><span style="color: #008000">//</span><span style="color: #008000"> 文件路径</span>
<span style="color: #0000ff">var</span> paths =<span style="color: #000000"> {
  pug: {
    src: </span>'src/pug/pages/*.pug'<span style="color: #000000">,
    dest: </span>'dist/html/'<span style="color: #000000">
  },
  less: {
    src: </span>'src/less/main.less'<span style="color: #000000">,
    dest: </span>'dist/css/'<span style="color: #000000">
  },
  js: {
    src: [</span>'src/js/**/*.js', '!src/js/lib/*.js'<span style="color: #000000">],
    dest: </span>'dist/js/'<span style="color: #000000">
  },
  img: {
    src: </span>'src/img/**/*'<span style="color: #000000">,
    dest: </span>'dist/img/'<span style="color: #000000">
  }
};


</span><span style="color: #008000">//</span><span style="color: #008000"> 将pug文件转换为html</span>
gulp.task('pug', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.pug.src)
    .pipe(pug())
    .pipe(gulp.dest(paths.pug.dest));
});

</span><span style="color: #008000">//</span><span style="color: #008000"> 编译less文件</span>
gulp.task('less', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.less.src)
    .pipe(less({
      plugins: [autoprefix]
    }))
    .pipe(base64({
      maxsize: </span>8<span style="color: #000000">
    }))
    .pipe(cleanCSS({
      compatibility: </span>'ie8' <span style="color: #008000">//</span><span style="color: #008000"> 兼容性前缀保留</span>
<span style="color: #000000">    }))
    .pipe(rev())
    .pipe(gulp.dest(paths.less.dest))
    .pipe(rev.manifest())
    .pipe(gulp.dest(</span>'rev/css'<span style="color: #000000">))
});

</span><span style="color: #008000">//</span><span style="color: #008000"> 压缩图片</span>
gulp.task('img', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.img.src)
    .pipe(imagemin({
      optimizationLevel: </span>3<span style="color: #000000">,
      progressive: </span><span style="color: #0000ff">true</span><span style="color: #000000">,
      interlaced: </span><span style="color: #0000ff">true</span><span style="color: #000000">
    }))
    .pipe(gulp.dest(paths.img.dest));
});

</span><span style="color: #008000">//</span><span style="color: #008000"> 编译JS文件</span>
gulp.task('js', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span><span style="color: #000000"> gulp.src(paths.js.src)
    .pipe(babel({
      presets: [</span>'es2015'<span style="color: #000000">]
    }))
    .pipe(uglify())
    .pipe(rev())
    .pipe(gulp.dest(paths.js.dest))
    .pipe(rev.manifest())
    .pipe(gulp.dest(</span>'rev/js'<span style="color: #000000">));
});
</span><span style="color: #008000">//</span><span style="color: #008000"> 引用的外部 JS 库,不需要做压缩和打时间戳等处理</span><span style="color: #008000">
//</span><span style="color: #008000"> 所以直接复制就行</span>
gulp.task('copyJs', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span> gulp.src('src/js/lib/*.js'<span style="color: #000000">)
    .pipe(gulp.dest(</span>'dist/js/lib/'<span style="color: #000000">))
})

</span><span style="color: #008000">//</span><span style="color: #008000"> 替换加了MD5时间戳的文件</span>
gulp.task('rev', gulp.series(gulp.parallel('img64', 'less', 'js'), <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span> gulp.src(['rev/**/*.json', 'dist/html/*.html'<span style="color: #000000">])
    .pipe(revCollector({
      replaceReved: </span><span style="color: #0000ff">true</span><span style="color: #000000">
    }))
    .pipe(gulp.dest(paths.pug.dest));
}));
</span><span style="color: #008000">//</span><span style="color: #008000"> Clean 任务执行前,先清除之前生成的文件</span>
gulp.task('clean', <span style="color: #0000ff">function</span><span style="color: #000000">() {
  </span><span style="color: #0000ff">return</span> del('dist/'<span style="color: #000000">)
});

</span><span style="color: #008000">//</span><span style="color: #008000"> 默认任务,在命令行输入`gulp`来启动任务</span>
gulp.task('default', gulp.series('clean', gulp.series('img', gulp.parallel('rev', 'copyJs'))))

In the production environment, the code needs to be compressed and merged. In addition, every time the code is updated and a new version is released, in order for the user client to download the updated code, we also need to timestamp the CSS and JS files.

gulp-rev is a plug-in specifically designed to stamp files with MD5. After MD5 stamping, of course, the references in the HTML file also need to be changed. It will definitely be a very troublesome thing to manually change each one. So we also need the gulp-rev-collector plug-in to help us replace files stamped with MD5.

gulp-imgbase64, this plug-in can specify which img elements in the HTML file are converted to base64. If you need more personalized conversion, you can use this plug-in.

5.Project directory structure

XXX——

| — dist

  | — html

  | — css

  | — img

  | — js

   | — lib

| — dev

  | — html

  | — css

  | — img

  | — js

   | — lib

| — src

  | — pug

   | — components

   | — pages

   | — layout.pug

  | — less

   | — pages

   | — main.less

   | — reset.less

   | — common.less

| — feature.less

  | — img

  | — js

   | — lib

The src folder contains the main business code, which contains code that requires long-term maintenance.

The dev folder is where gulp generates code during development.

The

dist folder is where gulp generates code when generating.

In this configuration, I did not put the code generated through gulp during development in the src folder like many other people did, because that would cause a lot of reference troubles and separate the development and production The code environment is separated, which can keep the src folder pure without any messy code.

So for some files that have not been processed by gulp, I will copy them directly to the corresponding location in the dev or dist folder.

The dist folder will be cleared before each gulp task generates code, so we don't need to care about the contents of the dist folder.

The dev folder may have a lot of redundant files, but we don’t need to worry about it having any impact on us. It doesn’t matter if files are deleted or overwritten, we just need to ensure that the files in the src folder are correct.

The above is the detailed content of Gulp practical configuration (2) - small and medium-sized projects. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.