Skip to content

Instantly share code, notes, and snippets.

@jrschumacher
Last active March 25, 2024 16:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jrschumacher/943929c81e59a75b59f2eb849addcbf7 to your computer and use it in GitHub Desktop.
Save jrschumacher/943929c81e59a75b59f2eb849addcbf7 to your computer and use it in GitHub Desktop.
A terser script to minify all javascript files in a directory
const fs = require('fs')
const {sync: globSync} = require('glob')
const filesize = require('filesize')
const Terser = require('terser')
const options = require(process.env.TERSER_CONFIG || './terserrc.json')
const getSize = (file) => {
const {size} = fs.statSync(file)
return filesize(size)
}
const files = globSync(`${process.env.TERSER_DIST_PATH || './dist'}/*.js`)
files.map(file => {
console.log(`Minifying ${file} (${getSize(file)})`)
const terserResult = Terser.minify(fs.readFileSync(file, 'utf8'), options)
if (terserResult.error) {
console.log(`Minifying ${file} error.`, terserResult.error)
}
else {
fs.writeFileSync(file, terserResult.code, 'utf8');
console.log(`Minifying ${file} (${getSize(file)}) success.`)
}
})
{
"parse": {
"ecma": 8
},
"compress": {
"ecma": 5,
"warnings": false,
"arrows": false,
"collapse_vars": false,
"comparisons": false,
"computed_props": false,
"hoist_funs": false,
"hoist_props": false,
"hoist_vars": false,
"inline": false,
"loops": false,
"negate_iife": false,
"properties": false,
"reduce_funcs": false,
"reduce_vars": false,
"switches": false,
"toplevel": false,
"typeofs": false,
"booleans": true,
"if_return": true,
"sequences": true,
"unused": true,
"conditionals": true,
"dead_code": true,
"evaluate": true
},
"mangle": {
"safari10": true
},
"output": {
"ecma": 5,
"comments": false,
"ascii_only": true
}
}
@Seekinguser
Copy link

Hello!

I found your work yesterday! Could you please help me! Where canI find install notes?

@Seekinguser
Copy link

For example, if I have my js files is /folder/scripts/ - const files = globSync(${process.env.TERSER_DIST_PATH || './dist'}/*.js) - what the right way to set the path?

@jrschumacher
Copy link
Author

@Seekinguser I don't recall, but probably TERSER_CONFIG=/path/to/terserrc.json TERSER_DIST_PATH=/path/to/dist node terser.js

So if you have this file in ~/Projects/terser.js and you keep ~/Projects/ProjectA.terserrc.json near it, and you have ~/Projects/ProjectA which has a dist ~/Projects/ProjectA/dist then:

cd ~/Projects
TERSER_CONFIG=./ProjectA.terserrc.json TERSER_DIST_PATH=./ProjectA/dist node ./terser.js

This should minify the data in ~/Projects/ProjectA/dist.


Beyond this I'm not sure, good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment