Is UglifyJS the best choice for minifying client-side JavaScript, or is there a better

Looking to parse (and potentially modify) a JavaScript expression from within the language itself. Interested in markup for eval() expressions before actual evaluation.

Impressed by the UglifyJS README examples, but unfortunately requires node.js. Is there a way to run this on the client-side browser?

(Not an expert in JavaScript, so open to corrections if misunderstanding the platform)

If not possible, are there alternative JavaScript parsers available? Considering options such as LintJS, esprima, or similar alternatives.

Answer №1

UglifyJS can be used in both the browser and NodeJS, similar to Esprima's functionality (though it's advisable to verify browser compatibility specs for each). You can experiment with UglifyJS in the browser (Chrome is recommended) by visiting the UglifyJS site and accessing your inspector console to enter:

var ast = UglifyJS.parse("var foo= 1")

You can then analyze the AST data. For instance, to retrieve the name of the variable declaration, use:

ast.body[0].definitions[0].name.name // returns "foo"

If you wish to alter the AST tree structure, review the architecture and create your own AST nodes to expand the tree. The UglifyJS documentation is decent, although the format for examining the structure may seem a bit customized (pop-up dialogs can become tedious; I ended up developing my own documentation parser for a more enjoyable study experience). The AST nodes are simply basic objects (no need for constructors or prototypes, just object literals containing straightforward property values or sub objects/arrays of objects); as long as they possess all necessary properties and AST structures, you'll have a valid AST tree. For example, you could modify the variable name like so:

ast.body[0].definitions[0].name.name = "bar";

After modifying the tree, you can convert it back into Javascript source code using the code generator feature. For example:

// assuming the variable ast already exists as mentioned above
var stream = UglifyJS.OutputStream(); // there are customizable options available for basic formatting
ast.print(stream);
var code = stream.toString();
console.log(code); // results in "var bar=1;"

Both UglifyJS and Esprima are fantastic tools. Esprima utilizes the Spider Monkey AST format, a widely recognized standard for Javascript ASTs, while Uglify employs its own AST model. Personally, I find that Esprima's AST format is neat yet lengthy, whereas UglifyJS opts for brevity although cleanliness may vary. Additionally, tools like Escodegen are available for Esprima to generate code akin to UglifyJS.

It's beneficial to explore these tools and determine which suits your preferences best; they all offer similar capabilities and enable efficient automation of refactoring and code analysis tasks like never before.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What types of functions can I link to jQuery's on() event handler?

Are there any additional events that can be used with jQuery's on() function besides click, mouseover, and mouseleave? I have been searching for documentation on this but can't seem to find any. ...

Tips for verifying a missing 'Access-Control-Allow-Origin' header error

Is it feasible, while working with XMLHttpRequest in JavaScript, to differentiate between these two types of errors: GET request completely failed/No 'Access-Control-Allow-Origin' header? https://i.sstatic.net/Zas2z.png It seems that the readyS ...

When utilizing the http.post method, the req.body is not being populated as expected

I am puzzled by the fact that the req.body appears to be empty... app.js utilizes the body-parser middleware() var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/in ...

In the frontend, I seem to have trouble accessing elements of an array using bracket notation, yet strangely it works flawlessly in the backend

I am encountering a peculiar issue as a newcomer to coding. I have an array retrieved from the backend database, and my goal is to access individual elements of this array in the frontend using bracket notation. While I can successfully access the elements ...

"Express API POST request functions successfully on Postman, however encounters difficulties when used with AJAX

My goal is to send an AJAX request from JavaScript to my ExpressJS Rest API. Unfortunately, the POST call is not working in JavaScript. Interestingly, when I use Postman, the same JSON data with the same headers works perfectly. Here is the error I&apos ...

Telegram Integration Using Firebase - Sending POST Requests

Currently, I am in the process of creating a Firebase cloud function (using Express) that performs the following tasks: - Checking if a user exists in the database. - Sending a message to the Telegram API based on whether the user exists or not. The probl ...

Check if the div has been clicked, even if its child elements have also

Is it possible to check if both a div and its child are clicked using jQuery? $('div').click(function(e){ if(e.target.id == 'test') alert(e.target.id); }); I have a specific div with an id of #test in my HTML code, and wh ...

Comparing AngularJS Style Guides: Insights from Todd Motto, John Papa, and Minko Gechev

As someone new to Angular, I am eager to establish good practices right from the start. I have discovered three compelling Angular style guides, each with its own strengths. However, since I lack experience with large Angular applications, I find myself un ...

Unlocking the Count of ng-repeat Elements in Angular JS 1

I'm curious about how to obtain the count of items in ng-repeat using AngularJS. In this particular code, I'm interested in finding out the count of "skill" because I want to set a limit on it. If the count of skills exceeds 5, I only want to dis ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Error: Spy creation was anticipated to have been invoked

Currently, I am in the process of writing unit test cases for an Angular 7 Component that utilizes an async service. Unfortunately, I encountered the following error: Error: Expected spy create to have been called once. It was called 0 times. Below is t ...

Is it an issue with Ajax not returning just the JSON output data, but instead displaying the entire loaded view code in CodeIgniter?

I have a script where I am trying to fetch data from a Codeigniter controller. The JSON data retrieved in the view using AJAX is displaying along with HTML code. Can anyone help me figure out how to only get the JSON data and assign it to a variable? The ...

Retrieving a list from a C# function using JQuery ajax

I find myself in a bit of a dilemma while attempting to integrate C# and jQuery seamlessly. Within the same solution/project, I have a .cs file and a javascript document. The C# function I've written returns a list of strings, which I aim to append to ...

What is the most effective way to use Javascript to update an image depending on the selected value in a dropdown

My JavaScript skills are limited, but I have successfully created a form with 4 drop-down selection boxes on the left side for users to choose from (State, Car, Year, Condition). After making their selections, users can click a 'calculate' butto ...

Error: Morris.js is unable to access the property 'x' because it is undefined

Seeking assistance in utilizing Morris.js to create an area chart using data from a JSON file. The JSON data is as follows: [{"period": 0, "time": 121.0}, {"period": 1, "time": 102.0}, {"period": 2, "time": 104.0}, {"period": 3, "time": 91.0}, {"period": ...

What is the correct way to retrieve a JSON object instead of getting [Object object]?

Creating a basic web scraper integrated with mongoDB. Even though the API returns the JSON object in the correct format, when trying to append it to a bootstrap card on the page, I'm getting [Object object]. Below is my JavaScript code running on th ...

Why isn't the Vue component refreshing its view after the state changes in Vuex?

Recently, I delved into the world of vue and learned about its redux counterpart vuex. However, I'm facing an issue where changes in the vuex state are not triggering reactive updates to the view in a vue component. export const store = new Vuex.Store ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

Guide on loading '.obj' files with multiple '.mtl' files using Three.js

I am attempting to load the cube.obj file which references multiple cube_*.mtl files, each of which utilize texture images in the format *.png. The resources can be found here. My goal is to dynamically load objects with the same geometry but different mat ...

Utilize the capabilities of the addEventListener method to directly access EventTarget without the need

Here is a code snippet that removes the focus from a select element after it is clicked: const select = document.querySelector('select'); select.addEventListener('focus', () => { select.blur(); }); <select> <option> ...