This is the 15th day of my participation in Gwen Challenge

preface

In the previous article, I covered gulp tasks, reading and output files, and pipes. In this article, I will show you how to manage HTML well.

Compress HTML code

Gulp-htmlmin is a plug-in for gulp to compress HTML. The following uses gulp-htmlmin.

Run the following command to install

npm i -D gulp-htmlmin
Copy the code

Modify the configuration of gulpfile.js

const { series, parallel, src, dest } = require('gulp')

const htmlmin = require('gulp-htmlmin')

function html() {
  return src('src/**/*.html')
    .pipe(htmlmin({
      removeComments: true.// Clear HTML comments
      collapseWhitespace: true.HTML / / compression
      collapseBooleanAttributes: true.// Omit Boolean values  ==> 
      removeEmptyAttributes: true. ==> 
      removeScriptTypeAttributes: true.// Delete 
      removeStyleLinkTypeAttributes: true.// Delete 
      minifyJS: true.// Compress the page JS
      minifyCSS: true // Compress the page CSS
    }))
    .pipe(dest('dist'))}exports.build = series(html)
Copy the code

In the last article, I wrote index.html in SRC, which reads as follows.

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Home page</title>
</head>
<body>
  
</body>
</html>
Copy the code

For convenience and consistency, we first write the build shortcut command in package.json, using NPM run build instead of gulp build.

{..."scripts": {..."build": "gulp build",}}Copy the code

Run the build command NPM run build

We can see that the index.html in the dist directory is compressed.

Reuse template

Gulp-file-include copies the code of the specified HTML file to an HTML file. For example: All pages need to have the same header and foot, and it would be redundant to write the header and foot once on every page. Using gulp-file-include, you can separate the header and foot code from the main page.

The installation

npm i -D gulp-file-include
Copy the code

Gulpfile. Js configuration

.const fileinclude = require('gulp-file-include')

function html() {
  return src(['src/**/*.html'.'! src/include/**.html'])
    .pipe(fileinclude({
      prefix: '@ @'.// Reference symbol
      basepath: './src/include' // Reference the file path
    }))
    .pipe(htmlmin({
      removeComments: true.// Clear HTML comments
      collapseWhitespace: true.HTML / / compression
      collapseBooleanAttributes: true.// Omit Boolean values  ==> 
      removeEmptyAttributes: true. ==> 
      removeScriptTypeAttributes: true.// Delete 
      removeStyleLinkTypeAttributes: true.// Delete 
      minifyJS: true.// Compress the page JS
      minifyCSS: true // Compress the page CSS
    }))
    .pipe(dest('dist'))}Copy the code

Note:

  1. In the gulpfile.js configuration,srcThe SRC () method has been changed to an array, meaning that all HTML files in the SRC directory are processed, but not those in SRC /include. Because the files in the include folder are “components” that are imported into HTML.
  2. Fileinclude should be written before HTMLmin. All code should be imported into HTML and then compressed.

Create an include folder in the SRC directory with a header. HTML and a footer. HTML and write the following code inside.

header.html

<div>The head</div>
Copy the code

footer.html

Foot in the < div > < / div >Copy the code

Header. HTML and footer. HTML don’t need HTML, body, etc. Remember that the content inside them is imported into index.html.

Use @@ to introduce headers and feet in index.html.

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Home page</title>
</head>
<body>
  @@include('./header.html')
  <div>Home page content</div>
  @@include('./footer.html')
</body>
</html>
Copy the code

After running the NPM run build command, we can see that dist/index.html has a lot of header and foot code.

At this point, the HTML is taken care of, but the current project is not good enough to optimize the packaging process, and there is no devServer like WebPack for rapid site development, so we can continue to add the following plug-ins to improve the project.

Optimizing the compilation process

Changed is a plug-in that only lets changed files through the pipe, which can improve efficiency by preventing unchanged files from being recompiled.

The installation

npm i -D gulp-changed
Copy the code

gulpfile.js

.const changed = require('gulp-changed')

function html() {
  return src(['src/**/*.html'.'! src/include/**.html'])
    .pipe(changed('dist'))
    .pipe(fileinclude({
      prefix: '@ @'.// Reference symbol
      basepath: './src/include' // Reference the file path
    }))
    .pipe(htmlmin({
      removeComments: true.// Clear HTML comments
      collapseWhitespace: true.HTML / / compression
      collapseBooleanAttributes: true.// Omit Boolean values  ==> 
      removeEmptyAttributes: true. ==> 
      removeScriptTypeAttributes: true.// Delete 
      removeStyleLinkTypeAttributes: true.// Delete 
      minifyJS: true.// Compress the page JS
      minifyCSS: true // Compress the page CSS
    }))
    .pipe(dest('dist'))}Copy the code

Changed needs to know the location of the target directory in advance to know which files have not been changed, so the input parameter in CHANGED is the dist path.

Changed can be used to manage not only HTML, but other resources as well, and will be used in later articles.

Local server

Gulp-webserver is a local server with hot replacement, proxy and other functions, which can be used to develop programs more quickly.

The installation

npm i -D gulp-webserver
Copy the code

gulpfile.js

.const webserver = require('gulp-webserver')...function devServer() {
  return src('dist').pipe(webserver({
    port: 3000.livereload: true.// Whether to load in real time
    // directoryListing: true, // Whether to enable directory browsing
    // open: true, // Whether to open automatically
    // Proxies: [// Proxies can be used to solve cross-domain problems
    // {source: '/api', target: 'http://xxxx.com', options: {headers: {"Content-Type": 'application/x-www-form-urlencoded'}}}
    // ]}}))exports.default = series(html, devServer) // Add this command
exports.build = series(html)
Copy the code

Similarly, add development shortcut commands in package.json for convenience and consistency.

{..."scripts": {..."dev": "gulp"},... }Copy the code

Run NPM run dev and type localhost:3000 in your browser to see our compiled content.

But if we change the content in SRC /index.html, it doesn’t seem like the browser automatically loads the new content, because we didn’t recompile the code into the dist directory. If we change the content in dist/index.html, we can see that the browser automatically updates the content. So how do you monitor the content in SRC?

Gulp’s watch method is used here.

Add a watch to listen for the HTML file in the SRC directory and re-execute the HTML task if the HTML file changes.

const { series, parallel, src, dest, watch } = require('gulp')...function watcher() {
  watch('src/**/*.html', series(html))
}

exports.default = series(html, devServer, watcher)
...
Copy the code

If you run NPM run dev at this point, you can see that changing SRC /index.html triggers a browser refresh.

Gulp-webserver can also write proxies to solve cross-domain problems, the above code has been posted, remove the comment, modify the value can be used, here does not elaborate on how to use.

Note: HTML changes in the include folder do not refresh the browser. At first I thought they were SRC ([‘ SRC /**/*.html’, ‘! SRC /include/**.html’]) ‘! SRC /include/**.html’, but I deleted it and it didn’t work. We can only manually refresh by deleting the @@include of index. HTML and then adding it back to save, or by re-running NPM run dev. I can’t find the problem. Maybe it’s a plugin problem. If you know, please tell me in the comments section.

Delete old files

The old dist files will not be deleted automatically before compilation, so we need to manually delete the dist directory every time to prevent the existence of old files, but this will be troublesome, we can use the DEL plug-in and gulp watch to automatically delete files.

The installation

npm i -D del
Copy the code

gulpfile.js

const del = require('del')...function clean() {
  return del('dist')}exports.default = series(clean, html, devServer, watcher)
exports.build = series(clean, html)
Copy the code

Each time we run NPM run build or NPM run dev, the program removes the dist directory beforehand.

If you delete the SRC source file during NPM run dev, you may end up leaving the dist file behind.

You can run NPM run dev and create a new aa. HTML file in SRC. Dist will pack up a new aa. HTML file in dist. Then delete SRC /aa. HTML and you will find that the aa. HTML file is still in dist.

To fix this, we need to fix watcher.

gulpfile.js

const Path = require('path')

function watcher() {
  watch('src/**/*.html', series(html)).on('unlink'.function (path) {
    del('dist/**/' + Path.basename(path))
  })
}
Copy the code

This code means that the listener listening for HTML listens for the “delete” event, and when the HTML file is deleted, the corresponding HTML file in dist is also deleted.

Complete the project

On August 30, 2021, I reorganized the project and put it on Gitee. You can clone it and use it directly. The code submission record sequence is consistent with the sequence of my series of articles.

Gitee Library link: gitee.com/only1zhuo/g…

“The Use of GULP” series

  • Use of GULP (1) : Start (juejin. Cn)
  • Using gulp (2) : HTML (juejin. Cn)
  • Using gulp (3) : processing js (juejin. Cn)
  • Using gulp (4) : Handling CSS (juejin.cn)
  • Use of gulp (5) : processing images (juejin. Cn)
  • Use of Gulp (6) : Using Webpack stream modularization (juejin. Cn)
  • Using gulp (7) : Using Babel to translate JS (juejin.cn)
  • Use of GULP (8) : Separation environment (juejin. Cn)