This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Build an automated development environment for Node.js

[Tool Preparation], [Start], [Step 1],

Build a front-end engineering environment

usegulp-htmlmintool

To output the HTML file in SRC and compress it, we use the gulp-htmlmin tool

  • Compressed HTML
const htmlmin = require('gulp-htmlmin')
// Processing HTML, output HTML files from SRC to dist
gulp.task('handle:html'.function ({
  return gulp.src('./src/views/*/*.html') .pipe(htmlmin(...) ) .pipe(gulp.dest('./dist'))})Copy the code

To make it easier to maintain the configuration, we created config/index.js. We defined the config object in this file, where we would store some of the global configuration

  • Global configuration
const config = {
  htmloptions: {
    // HTML compression configuration
    removeCommentstrue.// Clear HTML comments
    collapseWhitespacetrue.HTML / / compression
    collapseBooleanAttributestrue.==> 
    removeEmptyAttributestrue. ==> 
    removeScriptTypeAttributestrue.// Delete 
    removeStyleLinkTypeAttributestrue.// Delete 
    minifyJStrue.// Compress the page JS
    minifyCSStrue.// Compress the page CSS}},Copy the code

In order for gulp file.js to import and access the Config object, we need to expose it


// The config is exposed only once for use elsewhere

module.exports = config

Copy the code

This allows you to introduce the configuration object in gulp file.js


// Global configuration because it is a module. So I don't have to write.js
// const config = require('./config/index')
const config = require('./config'// In this case, we can omit index because we are taking index
/ /...
gulp.task('handle:html'.function ({
  return gulp
    .src('./src/views/*/*.html')
    .pipe(htmlmin(config.htmloptions))
    .pipe(gulp.dest('./dist'))})Copy the code

We’ve also made a file listen to ensure that we can perform this task if we change the HTML file

/ / to monitor function gulp. Task (' watch ', function () {gulp. Watch (')/SRC/views / * / *) HTML ', [' handle: HTML])}) / / the default task gulp. Task (' default '[' handle: HTML', 'watch'])Copy the code

So we execute gulp command, the environment run

1. Change the NPM start startup mode

Most environments are run by NPM start. Package. json has a scripts configuration item where you can configure shortcuts such as:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "htmlmin": "gulp htmlmin",
    "watch": "gulp watch",
    "dev": "gulp",
    "start": "npm run dev"
  },
Copy the code

In this case, you can use NPM run htmlmin and NPM run watch operations to execute the corresponding command, because start is special, so you can directly NPM start to run

Set up a hot update server using Gulp-Connect

  • 01. Create a hot update server
gulp.task('server'.function ({
  connect.server(config.serveroptions)
})

Copy the code
  • 02. Server configuration

serveroptions: {// Hot update service
  root'./dist'.port8000.livereloadtrue
}
Copy the code

Because the page needs to be refreshed when the file is updated, the reload task needs to be configured and executed after the file changes

  • The task of getting the server to refresh

gulp.task('reload'.function ({
  return gulp
    .src('./dist/**/*.html'// Reload all HTML files
    .pipe(connect.reload())

})

gulp.task('watch'.function ({
  gulp.watch('./src/views/*/*.html'['handle:html'.'reload'])})Copy the code
  • 3. Processed THE CSS to achieve the effect of merging and compression

First, configure the CSS in the global configuration file


cssoptions: {/ / CSS configuration

  'index': { // Index the CSS of the page

    'common': [ // index The common.min. CSS file that needs to be merged after page processing

      './src/stylesheets/reset.css'.'./src/views/index/stylesheets/common/*.css'].// index After page processing index.min. CSS to merge files

    'index''./src/views/index/stylesheets/index/*.css'

  },

  'list': {

    'list': [

      './src/stylesheets/reset.css'.'./src/views/list/*/*.css']}}Copy the code

The above configuration needs to be modified according to the CSS file. The configuration in gulp is as follows:

Const merge = require('merge-stream') const merge = require('merge-stream')
// Process CSS, merge CSS, compress CSS, prefix, output
gulp.task('handle:css'.function ({
  // 1. Hope to be able to merge into multiple CSS, more flexible 2
  let streams = [] // Store an array of the following file streams
  for (const page in config.cssoptions) {
    // Iterate over multiple pages
    for (const file in config.cssoptions[page]) {
      // Iterate through multiple packaging CSS file configurations for each page
      let stream = gulp
        .src(config.cssoptions[page][file])
        .pipe(
          autoprefixer({
            // Automatic prefix
            browsers: [
              'last 2 versions'.'Safari >0'.'Explorer >0'.'Edge >0'.'Opera >0'.'Firefox >=20',].// Last 2 Versions - the latest two versions of major browsers
            cascadefalse.// Whether to beautify the property value by default: true like this:
            // -webkit-transform: rotate(45deg);
            // transform: rotate(45deg);
            removetrue.// Whether to remove unnecessary prefixes. Default: true
          })
        )

        .pipe(concat(file + '.css')) // Merge files
        .pipe(minifycss()) // Compress the file

        .pipe(rename({ suffix'.min' })) / / renamed

        .pipe(gulp.dest('./dist/' + page + '/css')) // Output to the corresponding directory
      streams.push(stream) // Store the current file stream in an array}}returnmerge(... streams)// Merge multiple file streams

  / /... Is an operator of es6 var = [1, 2, 3, 4] var b = [... a, 5, 6] / / b:,2,3,4,5,6,7 [1]

  // var a = { x: 1, y: 2 } var b = { z: 3, ...a } //  b: { x: 1, y: 2, z: 3 }
})

Copy the code
  • Listening to the CSS

gulp.task('watch'.function ({

  gulp.watch('./src/views/*/*.html'['handle:html'.'reload'])

  gulp.watch('./src/**/*.css'['handle:css'.'reload'])})Copy the code

Below update preview, keep up with the rhythm refueling

Next, I will continue to learn Node.js to complete the setup of our automated development environment,

Improve development efficiency and empower our development efficiency!

Keep up with the pace of progress, forward refueling

Come on!! go~