Keep es5 explicit "using strict"; with gulp-uglify

event 2024-07-14 visibility 42 comment 0 insights
more_vert
insights Stats
Raymond Raymond Frontend & JavaScript

About Xml Xhtml Xslt Dhtml Css Javascript

Kontext uses some modules that use explicit strict mode ("using strict";) which was introduced in ES5. After I upgrade some of the gulp packages to the latest, some frontend pages stop working properly. After debugging and compare the generated uglified script file, I found the explicit strict mode code was removed for certain packages.

The code snippet looks like the following:

"use strict";

const gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    uglify_gulp = require("gulp-uglify"),

const paths = {
    webroot: "./wwwroot/",
    node_modules: "./node_modules/",
    draw: "./wwwroot/draw/"
};

const uglify = () => uglify_gulp({
    mangle: true,
    output: {
        comments: /^!/,
    }
    });

gulp.task("min:js", () => {
    return gulp.src(paths.jsFilesDraw, { base: "." })
        .pipe(uglify())
        .pipe(concat(paths.concatJsDestDraw))
        .pipe(gulp.dest("."));

Root cause

The issue occurred because gulp-uglify version 5 by default uses UglifyJS 3 to minify JavaScript files. There are a number of options of the package as documented on GitHub. The one that caused the issue for my project is the following option:

  • module (default: true) — process input as ES module, i.e. implicit "use strict"; and support for top-level await. When explicitly specified, also enables toplevel.

By default ES module (introduced in ES6) is used. Hence to fix the issue we just need to override the default behavior.

Solution

The solution is to change module option to false.

const uglify_gulp = require("gulp-uglify")
// ...
const uglify = () => uglify_gulp({
    mangle: true,
    output: {
        comments: /^!/,
    },
    module: false
});
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts