使用Gulp-Uglify压缩Angular 1.6.8 JavaScript代码失败求助
let Declaration Hey there! I get where the confusion is—even though your Angular module declaration looks similar to ES5 code, the let keyword is actually an ES6 feature, and the standard gulp-uglify package relies on UglifyJS v3 which doesn’t handle untranspiled ES6 syntax out of the box. That’s exactly why it’s throwing an error on line 2, even if the rest of the code seems compatible.
Here are two solid solutions to fix this issue:
Option 1: Transpile ES6 to ES5 with Babel First
This is the most robust approach, especially if you’re using other ES6 features elsewhere in your codebase.
Install the required dependencies:
npm install gulp-babel @babel/core @babel/preset-env --save-devUpdate your
gulpfile.jsto add the Babel transpilation step before uglifying:const gulp = require('gulp'); const uglify = require('gulp-uglify'); const pump = require('pump'); const babel = require('gulp-babel'); gulp.task('compress', function(cb) { pump([ gulp.src('app.js'), babel({ presets: ['@babel/preset-env'] }), uglify(), gulp.dest('dist') ], cb); });
Option 2: Use an ES6-Compatible Uglify Package
If you don’t want to add Babel to your workflow, you can switch to gulp-uglify-es, which supports ES6 syntax directly.
Install the package:
npm install gulp-uglify-es --save-devUpdate your
gulpfile.jsto use the new package:const gulp = require('gulp'); const uglify = require('gulp-uglify-es').default; const pump = require('pump'); gulp.task('compress', function(cb) { pump([ gulp.src('app.js'), uglify(), gulp.dest('dist') ], cb); });
Quick Temporary Fix (Not Recommended for Full Projects)
If you just want to test with this specific line, you can replace let with var (the ES5 equivalent) in your app.js:
var app = angular.module("app", ["ngRoute"]);
Note: This only fixes this single line—if you have other ES6 features in your code, you’ll still run into issues, so the first two options are better for long-term use.
After implementing either option, run your gulp compress task again—this should resolve the error on line 2.
内容的提问来源于stack exchange,提问作者Alexander

