Javascript 如何解决 Gulp 上的这个缩小错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38886840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:59:56  来源:igfitidea点击:

How to solve this minification error on Gulp?

javascriptgulp

提问by StackOverflower

I'm getting below error running this command

运行此命令时出现以下错误

gulp.task('minify', function () {
    return gulp
      .src('public/app/js/myapp.bundle.js')
      .pipe(uglify())
      .pipe(gulp.dest('public/app/js/myapp.bundle.min.js'));
});

GulpUglifyError: unable to minify JavaScript Caused by: SyntaxError: Unexpected token: name (MenuItem) (line: 1628, col: 18, pos: 53569)

GulpUglifyError:无法缩小 JavaScript 导致:语法错误:意外标记:名称(MenuItem)(行:1628,列:18,位置:53569)

Code on that location is this

该位置的代码是这样的

 setters: [],
 execute: function () {
     class MenuItem {  // <-- line 1628

What's wrong?

怎么了?

回答by StriplingWarrior

UglifyJS does not currently supportEcmaScript 6 structures like classes.

UglifyJS目前不支持像 classes 这样的EcmaScript 6 结构。

You'll probably need to run your JavaScript through a transpiler step first, or find a minifier that knows what to do with ES6 code.

您可能需要首先通过转译器步骤运行您的 JavaScript,或者找到一个知道如何处理 ES6 代码的压缩器。

Update 2017-06-17

更新 2017-06-17

The branch of UglifyJS that is designed to work with ES6 is now published as uglify-eson npm.

设计用于 ES6 的 UglifyJS 分支现在uglify-es在 npm 上发布。

Update 2018-09-10

更新 2018-09-10

terseris the new uglify-es, uglify-esis no longer maintained.

terser是新的uglify-esuglify-es不再维护

If using gulpboth npmjs gulp-uglify-esand npmjs gulp-terserpackages support terser.

如果使用吞掉npmjs一饮而尽,丑化-ESnpmjs一饮而尽,更简洁的包支持更简洁。

npm install gulp-terser --save-dev
const gulp = require('gulp');
const terser = require('gulp-terser');

function es(){
  return gulp.src('./src/index.js')
    .pipe(terser())
    .pipe(gulp.dest('./build'))
}

gulp.task('default', es);

回答by Adam Reis

If you run into this problem and you havein fact a transpiler step like Babel, make sure that you include the proper Babel preset in you .babelrcfile. Otherwise Babel will simply leave your code as is.

如果您遇到这个问题,你其实是一个transpiler一步通天塔一样,请确保您在您正确的巴贝尔预设.babelrc文件。否则 Babel 只会让你的代码保持原样。

E.g.

例如

{
  "presets": ["es2015"]
}