preface

Recently, we are making a requirement, because we pack and form a static file and then submit it to Git, and finally the distribution system synchronizes the code to the server. Our entire process looks like this: 1. NPM run build….. The main problem is that when NPM run bulid, you need to wait for the package to complete, and this process is time-consuming. So you just sit back and wait, and then you commit to Git when you’re done packing. Therefore, I am wondering if there is a way to write a Node program to execute the Node program during NPM run build, use inquirer to ask for the commit message submitted by the user, and then automatically submit it to Git after packaging, so that we don’t have to wait for the packaging process. In addition, we can perform other necessary operations by executing the Node program. For example, in my project, CSS and images were not compressed due to historical problems. And CSS is imported through HTML, not import in JS (import CSS can be compressed through Webpack, and HTML link import I can’t find webpack compression method, Let me know in the comments if you know how to package the CSS imported in this way), so I can write some gulp programs in the Node program to compress the images and CSS. The whole idea is like this, how to do, the guest officer don’t worry, wait for me to say slowly.

Install dependencies

The first is the commit message that needs to accept user input for git commit, so we need the Inquire module. Then we need to commit git via Node, so we need the simple-Git module. Then we need to obtain the local branch which is the current branch, so that the simple- Git commit can be committed to the current branch, so we need the Git-branch module. Then you need to use gulp and gulp CSS and image compression, so you need to rely on gulp, gulp-minify-CSS, gulp-iamgemin

These modules are important dependencies of the program

Write a build.js wrapper

Accept user input & call Webpack to wrap the code
const ora = require('ora')
const {prompt} = require('inquirer')

const webpackConfig = require('./webpack.config.js')
const webpack = require('webpack')

const spinner = ora('building.... 'Const question = [{const question = [{type: 'input',
        name: 'commitMessage',
        message: 'Please input commit message:',
        validate(val) {
          if(val === ' ') {return 'commit messag is required'
          }
          return true
        }
    }
]

prompt(question).then(({commitMessage}) => {
    spinner.start()
    webpack(webpackConfig, (err, stats) => {
        spinner.stop()
        if(err) throw err
    
        if(stats.hasErrors()) {
            console.log(chalk.red('build failed with errors \n')) process.exit(1)} // After webpack is finished, call gulp to compress CSS and images})Copy the code
Gulp is called to compress CSS and images
const gulp = require('gulp')
const minifyCSS = require('gulp-minify-css')
const imagemin = require('gulp-imagemin')
const pngquant = require('imagemin-pngquant'// Compress the CSS file gulp.task('css'.function () {
    gulp.src('src/css/*.css')
        .pipe(minifyCSS())
        .pipe(gulp.dest('dist/css')}) // Compress all images under images gulp.task('image'.function() {return gulp.src('src/images/*.*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{
                removeViewBox: false
            }],
            use: [pngquant({
                quality: '100'
            })]
        }))
        .pipe(gulp.dest('dist/images'// Define a default task, which depends on the CSS task and the image task gulp.task('default'['css'.'image'].function() {// All tasks completed callback, so code submitted to Git is here}) // Start task gulp.start('default')
Copy the code
Commit code to Git
const git = require('simple-git')()
const branch = require('git-branch')

git.add(['-A'].commit(commitMessage) // commitMessage from the.push('origin', branch.sync()) // branch.sync() gets the current local branchCopy the code

Through these three steps, we have completed the one-click implementation of WebPack packaging, gulp compression of CSS and images, and Git submission. The final code is build.js as follows:

const ora = require('ora')
const {prompt} = require('inquirer')
const chalk = require('chalk')
const webpackConfig = require('./webpack.config.js')
const webpack = require('webpack')

const git = require('simple-git')()
const branch = require('git-branch')

const gulp = require('gulp')
const minifyCSS = require('gulp-minify-css'// Get minify-css module (for compression of CSS) const imagemin = require('gulp-imagemin')
const pngquant = require('imagemin-pngquant')

const spinner = ora('building.... ')
const question = [
    {
        type: 'input',
        name: 'commitMessage',
        message: 'Please input commit message:',
        validate(val) {
          if(val === ' ') {return 'commit messag is required'
          }
          return true
        }
    }
]

prompt(question).then(({commitMessage}) => {
    spinner.start()
    webpack(webpackConfig, (err, stats) => {
        spinner.stop()
        if(err) throw err
    
        if(stats.hasErrors()) {
            console.log(chalk.red('build failed with errors \n')) process.exit(1)} // Zip CSS file gulp.task('css'.function () {
            gulp.src('src/css/*.css')
                .pipe(minifyCSS())
                .pipe(gulp.dest('dist/css')}) // Compress all images under images gulp.task('image'.function() {return gulp.src('src/images/*.*')
                .pipe(imagemin({
                    progressive: true,
                    svgoPlugins: [{
                        removeViewBox: false
                    }],
                    use: [pngquant({
                        quality: '100'
                    })]
                }))
                .pipe(gulp.dest('dist/images'// Define a default task, which depends on the CSS task and the image task gulp.task('default'['css'.'image'].function() {// After the task is complete, commit to git. Add ([)'-A'])
                .commit(commitMessage)
                .push('origin', branch.sync())})'default')})})Copy the code
Modify the package. The json
"scripts": {
    "build": "node build.js"
  },
Copy the code

conclusion

Things that can be automated should not be done manually, so when we encounter some tasks that are relatively mechanized, multi-step and time-consuming in development, we should consider how to use code to complete automation. The above example, we can refer to the following, according to their own situation to modify and then can achieve a key to complete packaging & optimization & upload Git, is not feeling very convenient.