Skip to content

Terser installation

Terser is the JavaScript minifier. It processes JavaScript files as well as the compiled output from other languages like CoffeeScript and TypeScript and transpilers like Babel.

First, make sure you have installed the latest version of node.js (You may need to restart your computer after this step).

From NPM for use as a command-line app:

npm install terser -g

Output:

$ node -v
v17.3.0

$ npm install terser -g
added 6 packages, and audited 7 packages in 687ms
found 0 vulnerabilities

$ whereis terser
terser: /usr/local/nvm/versions/node/v17.3.0/bin/terser  

Usage is simple: GitHub - terser/terser: JavaScript parser, mangler and compressor toolkit for ES6+

Terser can take multiple input files. It's recommended that you pass the input files first, then pass the options. Terser will parse input files in sequence and apply any compression options. The files are parsed in the same global scope, that is, a reference from a file to some variable/function declared in another file will be matched properly.

If no input file is specified, Terser will read from STDIN. If you wish to pass your options before the input files, separate the two with a double dash to prevent input files from being used as option arguments:

terser --compress --mangle -- input.js

In Magento 2 specifically, we can implement the following after setup:static-content:deploy (Static asset) deployment is processed, but before that, we need to know the path of our Theme directory.

For example, let's try now to bundle the default Luma theme on a specific path for en_US language:

THEME_FOLDER=('/srv/public_html/pub/static/frontend/Magento/luma/en_US')

helper-75

Bundle files with the following line:

find ${THEME_FOLDER[@]} \( -name '*.js' -not -name '*.min.js' -not -name 'requirejs-bundle-config.js' \) -exec /usr/local/nvm/versions/node/v17.3.0/bin/terser \{} -c -m reserved=['$','jQuery','define','require','exports'] -o \{} \;  

Note: we skipped some of the patterns like *.min.js and requirejs-bundle-config.js, but if you are using MagePack or any other popular Bundling tool try to skip their Core bundle files generated. For example, for Baler tool:

-not -name 'core-bundle.js'

You can test and Minify them as well, but our advice is to test this before adding this to your Production environment.

helper-75

The last step is to clear Magento 2 cache and Redis if used and test. Run a new audit test, Measure page quality for example, and compare results before/after

helper-75

Disable Magento's built-in Minify mechanism for Javascript minify, integrate this tool in to your deployment process, and enjoy the performance boost.