This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

preface

In the current era of front-end engineering, we often use packaging tools such as WebPack/GULp to package projects for development and launch.

We also write globally immutable data in the code to represent a data, but there is a problem with writing directly in the code. When packaging, our parameters cannot be written into the code.

So at this point we can use WebPack to implement this function.

DefinePlugin

Webpack comes with a plugin called DefinePlugin that you can use to write global variables.

module.exports = ({ dev = true }) = > {
    entry: {},
    plugins: [
        new webpack.DefinePlugin({
            G_IS_DEV: dev
        })
    ],
    output: {}}Copy the code

A custom global variable for G_IS_DEV is implemented above.

Of course, I’m using gulp to manage this, using webpack-stream in gulp to use the file and pass in parameters.

The Webpack file is imported into gulp

We first need to install the webpack-stream package and then write it in gulpfile.js.

gulp.task('js'.() = > {
  return gulp
    .src('main.js')
      .pipe(
        // Import the WebPack configuration file here
        $.webpackStream(
          require('./webpack.config.js') ({dev: true
          })
        )
      )
      .pipe(gulp.dest(buildFolder))
  })
Copy the code

The above gulp task helps you to use WebPack to package js files and repackage them if main.js changes.

Finally, we can call this task in the default gulp task.

gulp.task("default", gulp.series("js"));
Copy the code

Some interesting effects

Do you know how to print the above data in the page?

Of course, you don’t write this data into the code manually.

We can use the above knowledge to implement this function.

In the Webpack configuration file write:

function getRevision(useLast = false){
    const commitHash = execSync('git rev-parse --short ' + (useLast ? 'HEAD^1' : 'HEAD')).toString(
      'ascii'
    )
    return commitHash.replace(/^\s+|\s+$/g.' ');
},
Copy the code

This function lets you get the short code that git commits.

You must know what to do by this point.

module.exports = ({ dev = true }) = > {
    entry: {},
    plugins: [
        new webpack.DefinePlugin({
            G_COMMIT_HASH: getRevision()
        })
    ],
    output: {}}Copy the code

Now we have a global variable called G_COMMIT_HASH.