Keep es5 explicit "using strict"; with gulp-uglify
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-levelawait
. When explicitly specified, also enablestoplevel
.
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
});