如何使用 gulp-uglify 缩小 ES6 函数?

当我运行 gulp 时,我收到以下错误:

When I run gulp I get the following error:

[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\servers\vagrant\workspace\awesome\web\tool\bundle.js',
showStack: false }

违规行包含箭头函数:

let zeroCount = numberArray.filter(v => v === 0).length

我知道我可以将其替换为以下内容,以通过放弃 ES6 语法来纠正缩小错误:

I know I can replace it with the following to remedy the minification error by abandoning ES6 syntax:

let zeroCount = numberArray.filter(function(v) {return v === 0;}).length

如何通过 gulp 缩小包含 ES6 功能的代码?

How can I minify code containing ES6 features via gulp?

推荐答案

你可以利用 gulp-babel 这样……

You can leverage gulp-babel as such...

const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

gulp.task('minify', () => {
  return gulp.src('src/**/*.js')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    // [...]
});

这将在管道的早期转译您的 es6,并在您缩小时生成广泛支持的纯"javascript.

This will transpile your es6 early in the pipeline and churn out as widely supported "plain" javascript by the time you minify.

可能需要注意 - 正如评论中所指出的 - 核心 babel 编译器作为 对等依赖 在这个插件中.如果核心库没有通过您的存储库中的另一个 dep 被拉下,请确保将其安装在您的最后.

May be important to note - as pointed out in comments - the core babel compiler ships as a peer dependency in this plugin. In case the core lib is not being pulled down via another dep in your repo, ensure this is installed on your end.

查看gulp-babel 作者指定 @babel/core (7.X).不过,稍旧的 babel-core (6.x) 也可以使用.我的猜测是作者(这两个项目都是一样的)正在重新组织他们的模块命名.无论哪种方式,两个 npm 安装端点都指向 https://github.com/babel/babel/tree/master/packages/babel-core,所以你可以使用以下任何一种......

Looking at the peer dependency in gulp-babel the author is specifying @babel/core (7.x). Though, the slightly older babel-core (6.x) will work as well. My guess is the author (who is the same for both projects) is in the midsts of reorganizing their module naming. Either way, both npm installation endpoints point to https://github.com/babel/babel/tree/master/packages/babel-core, so you'll be fine with either of the following...

npm install babel-core --save-dev

npm install @babel/core --save-dev

相关文章