Avoid having gulp's uglify plugin remove es6 code

I've encountered an issue while using gulp babel to compile es6. It seems that uglify is stripping out my es6 code completely. Strangely, I'm not receiving any errors in my command line during the process. Have you faced this problem before? Any suggestions on why this might be happening?

Here is a glimpse of my gulp task:

gulp.task('scripts', function () {
  return gulp.src('src/js/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

This is a snippet of my javascript code:

document.addEventListener('DOMContentLoaded', function (event) {
  console.log('ready to es6!');
  const foo = 4;
});

Upon compilation and minification, the resulting javascript code:

"use strict";document.addEventListener("DOMContentLoaded",function(e){console.log("ready to es6!")});
//# sourceMappingURL=scripts.js.map

As you can see, the const foo = 4 line is missing. Interestingly, removing the .pipe(babel()) from the gulp task allows the const declaration to be compiled correctly.

If it helps, here are the devDependencies listed:

"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"browser-sync": "^2.26.3",
"gulp": "^3.9.1",
"gulp-babel": "^8.0.0-beta.2",
"gulp-sass": "^4.0.2",
"gulp-sourcemaps": "^2.6.4",
"gulp-uglify": "^3.0.1",
"node-sass": "^4.11.0"
}

Answer №1

When using UglifyJS (a required component of gulp-uglify), there is an option for compression that automatically deletes any unused variables. In this case, since foo is never referenced, it is removed from the compressed source code.

According to the UglifyJS2 documentation:

Compression options: unused (default: true) -- eliminates unreferenced functions and variables (simple direct variable assignments are not considered references unless specified as "keep_assign")

Due to const foo = 4 being a straightforward variable assignment, it will not be included in the compressed code. You have the choice of assuming the unused code is unnecessary or modifying your gulp file accordingly:

gulp.task('scripts', function () {
  return gulp.src('src/js/*.js')
  .pipe(sourcemaps.init())
  .pipe(babel())
  .pipe(uglify({
     compress: {
       unused: false
     }
   }))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('dist/js'));
});

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

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

Detecting when an object exits the proximity of another object in ThreeJS

In my ThreeJS project, I have planes (Object3D) flying inside a sphere (Mesh). My goal is to detect when a plane collides with the border of the sphere so that I can remove it and respawn it in a different location within the sphere. I am wondering how I ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

Changing Coordinated Universal Time to Pacific Standard Time with Moment Timezone in JavaScript

I am attempting to set the variable "formattedLocalTime" to Pacific time using the following snippet of code. Despite the fact that the chrome debugger shows "locTime" as "Tue Sep 30 2014 16:17:25," which is the expected value, the formattedLocalTime on t ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

The code provided creates a web form using HTML and ExpressJS to store submitted information into a MongoDB database. However, there seems to be an issue with the 'post' method, while the 'get' method functions correctly

When I try to submit entries (name, email, address) on localhost:3000 in the browser, the 'post' function is not creating an object in the mongo database even though it works from the postman. The browser displays an error message saying "unable ...

The server is indicating that the validation for the user has failed due to the required field "foo" not being provided in the Node.js

An error message was received with the following details: "User validation failed: email: Path email is required., display_name: Path display_name is required." The error name returned is: ValidationError. The AJAX call code snippet is as follows: f ...

What is the best way to create a non-reactive value in Vue.js?

In my Vue.js app, I am facing an issue where an array value is becoming reactive even though I want it to remain un-reactive. The array should only be updated when a specific "refresh" action is completed. However, every time a new value is assigned to the ...

A step-by-step guide on showcasing Flickr images through API using a Justified Gallery

I am looking to integrate the Miromannino Justified Gallery () into my project, but I want it to showcase images fetched from Flickr. I have successfully implemented the code to retrieve photos from Flickr using the API through Ajax: $.ajax({ url ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

Determine the absolute path with respect to a different reference path, rather than the current working directory

One of the challenges I'm facing with my Node.js module is how to easily allow developers to edit the location of the dependencies relative to the module file itself. The issue arises because the current working directory, accessed through `process.cw ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...

Switch up your text display using JQuery and toggle between different texts

I have implemented a jQuery script to toggle the display of certain paragraphs when the "More" link is clicked. However, I am facing an issue where the link always displays "More" even after the content has been expanded. I want it to change to "Less" once ...

How can I make a recently added row clickable in an HTML table?

I have a table where each row is given the class ".clickablerow". I've set up an onclick function so that when a row is clicked, a dialog box appears allowing me to insert text above or below as a new row. The issue I'm facing is that even though ...

Systemjs running with Angular2 is causing 503 errors

I have developed a basic Angular2 app that does not make any external calls to resources. It consists of approximately 10 components, each with its own HTML and CSS files. I utilize gulp to generate a distribution package and deploy it to a testing environ ...

Eslint is actively monitoring files specified in the eslintignore to ensure they meet the set

I am currently working on a TypeScript project that is bundled by Webpack. I want to integrate Eslint into the project, but I have encountered an issue where Eslint watches compiled files even if they are listed in the .eslintignore file. .eslintignore: . ...

Is there a way to execute Javascript in Django without revealing static files?

When setting up payments on my Django site using Stripe, I realized that the .js file is visible under Sources in the developer tools when inspecting elements on any browser. This presents a potential security risk as anyone can access this file. How can ...