When we need to localize a project, we often have to do the mechanical and boring step of compressing the packaged output file and renaming it with a specific name. Doing this manually is fine, but it gets annoying too many times. So I wrote a little tool to do this in code.

The idea is very simple, using NodeJS + jszip folder packaging. So NPM install jszip needs to be executed in the project. After the installation is successful, write a JS file in the folder where you put webPack, along with the webpack file because this is essentially a package operation. The following

const [fs, JSZip] = [require('fs'), require('jszip')];
const zip = new JSZip();
// Read all parameters and compress folderName to targetname.zip
var args = process.argv.splice(2);
const [folderPath, targetName] = args;

// This zip object does not specify a folder directly, it needs to recursively search all files, using zip.file zip.folder to collect files
function readDir(obj, nowPath) {
    let files = fs.readdirSync(nowPath);
    files.forEach(fileName= > {
        let fillPath = `${nowPath}/${fileName}`;
        let file = fs.statSync(fillPath);
        if (file.isDirectory()) {
            let dirList = obj.folder(fileName);
            readDir(dirList, fillPath);
        } else{ obj.file(fileName, fs.readFileSync(fillPath)); }})}// Recursively collect a list of files
readDir(zip.folder(`${folderPath}`), `. /${folderPath}`);
// Generate compressed file data and write it to disk
zip.generateAsync({
    type: 'nodebuffer'.compression: "DEFLATE".compressionOptions: {
        level: 9
    }
}).then(content= > fs.writeFileSync(`. /${targetName}` , content , 'utf-8'));
Copy the code

This code can be run directly. By typing node zip-build.js the name of the folder you want to compress into and then customizing it in package.json, for example

{
  "name": "A test project."."version": "0.1.0 from"."private": true."main": "zip-build.jjs.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."doZip": "node zip-build.js dist output.zip"  
  },
  "keywords": []."author": ""."license": "ISC"."description": ""."dependencies": {
    "jszip": "^ 3.6.0"."webpack": "^ 5.36.0"}}Copy the code

This makes it very convenient to use the command directly compressed. The demo file is as follows