Skip to content

Instantly share code, notes, and snippets.

@itzsaga
Last active April 21, 2020 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itzsaga/7b4711e64875e9230a1de261a0a6fcb0 to your computer and use it in GitHub Desktop.
Save itzsaga/7b4711e64875e9230a1de261a0a6fcb0 to your computer and use it in GitHub Desktop.
Minification of a dist folder preserving swagger comments
var Terser = require("terser");
var fs = require("fs");
var path = require("path");
// This function takes a path and returns an array of the
// file paths in that directory that satisfy the requirements
function getAllFiles(dirPath, arrayOfFiles) {
let files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function(file) {
// Recursively go into each folder in the initial dirPath
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
} else {
// Build the array of file paths otherwise
arrayOfFiles.push(path.join(__dirname, dirPath, "/", file));
}
});
// Only return an array of files that end in .js
return arrayOfFiles.filter((path) => path.match(/\.js$/));
}
// The code that takes the array built above and rewrites
// the files in their minified state
function minifyFiles(filePaths) {
filePaths.forEach((filePath) => {
fs.writeFileSync(
filePath,
Terser.minify(fs.readFileSync(filePath, "utf8"), {
output: {
// Don't strip out comment blocks that contain
// this regex
comments: "/@swagger/"
},
}).code
);
});
}
// Call the script with the output directory of tsc as
// the argument to build the file list
const files = getAllFiles("./dist");
// Minify all the files output for the list
minifyFiles(files);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment