Javascript 如何使用 gulp-uglify 缩小 ES6 功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44958216/
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 02:48:58  来源:igfitidea点击:

How to minify ES6 functions with gulp-uglify?

javascriptnode.jsecmascript-6gulpgulp-uglify

提问by Don P

When I run gulp I get the following error:

当我运行 gulp 时,出现以下错误:

[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 }

The offending line contains an arrow function:

违规行包含一个箭头函数:

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

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

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

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

How can I minify code containing ES6 features via gulp?

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

采纳答案by scniro

You can leverage gulp-babelas such...

你可以像这样利用gulp-babel......

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())
    // [...]
});

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

这将在管道的早期转换您的 es6,并在您缩小时作为广泛支持的“普通”javascript 大量生产。



May be important to note- as pointed out in comments - the core babel compiler ships as a peer dependencyin 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.

可能需要注意- 正如评论中所指出的 - 核心 babel 编译器作为此插件中的对等依赖项提供。如果核心库没有通过你的 repo 中的另一个 dep 被拉下来,请确保它安装在你的一端。

Looking at the peer dependencyin gulp-babelthe 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...

综观对等体依赖性gulp-babel作者是指定@巴贝尔/芯(7.x中)。不过,稍微旧的babel-core(6.x) 也可以工作。我的猜测是作者(对于两个项目都是一样的)正在重新组织他们的模块命名。无论哪种方式,两个 npm 安装端点都指向https://github.com/babel/babel/tree/master/packages/babel-core,因此您可以使用以下任一方法...

npm install babel-core --save-dev

or

或者

npm install @babel/core --save-dev

回答by KayakinKoder

The accepted answer doesn't reallyanswer how to minify straight es6. If you want to minify es6 without transpiling, gulp-uglify v3.0.0 makes that possible:

接受的答案并没有真正回答如何缩小直接 es6。如果你想在不转译的情况下缩小 es6,gulp-uglify v3.0.0 使这成为可能:

Update March 2019

2019 年 3 月更新

Using my original answer, you definitely want to replace the uglify-es package with terser, as it seems uglify-es is no longer being maintained.

使用我的原始答案,您肯定想用terser替换uglify-es 包,因为似乎不再维护uglify-es 。

Original answer, still works:

原来的答案,仍然有效:

1.) First, upgrade your gulp-uglify package to > 3.0.0 If you're using yarn and want to update to the latest version:

1.) 首先,将你的 gulp-uglify 包升级到 > 3.0.0 如果你正在使用 yarn 并且想要更新到最新版本:

yarn upgrade gulp-uglify --latest

2.) Now you can use uglify-es, the "es6 version" of uglify, as so:

2.) 现在您可以使用 uglify-es,即 uglify 的“es6 版本”,如下所示:

const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const uglify = composer(uglifyes, console);

gulp.task('compress', function () {
    return gulp.src('src/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
});

For more info: https://www.npmjs.com/package/gulp-uglify

更多信息:https: //www.npmjs.com/package/gulp-uglify

回答by Vladimir Jovanovi?

You actually can uglify ES6 code without transpilation. Instead of gulp-uglifyplugin, use gulp-uglifyesplugin.

实际上,您可以在不进行转译的情况下丑化 ES6 代码。gulp-uglify使用gulp-uglifyes插件代替插件。

var gulp = require('gulp');
var rename = require('gulp-rename'); 
var uglify = require('gulp-uglifyes');
var plumber = require('gulp-plumber');
var plumberNotifier = require('gulp-plumber-notifier');
var sourcemaps = require('gulp-sourcemaps');
var runSequence = require('run-sequence').use(gulp);

gulp.task('minjs', function () {
  return gulp.src(['/dist/**/*.js', '!/dist/**/*.min.js'])
    .pipe(plumberNotifier())
    .pipe(sourcemaps.init())
    .pipe(uglify({ 
       mangle: false, 
       ecma: 6 
    }))
    .pipe(rename(function (path) {
      path.extname = '.min.js';
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('/dist'));
});

回答by Vladimir Jovanovi?

gulp-uglify:

吞咽丑化:

For ES6and newer.

对于ES6和更新。

  1. install: npm install --save-dev gulp-uglify
  2. install: npm install --save-dev gulp-babel @babel/core @babel/preset-env
  1. 安装: npm install --save-dev gulp-uglify
  2. 安装: npm install --save-dev gulp-babel @babel/core @babel/preset-env

Usage:

用法:

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

gulp.task('script', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest('src/dist'))
});

回答by Alena Levina

Using gulp-uglify-esinstead of gulp-uglify helped me perfectly to accomplish same as you're asking for

使用gulp-uglify-es而不是 gulp-uglify 帮助我完美地完成了你所要求的

回答by kumaheiyama

I worked at this for a while before getting it to work. As other answers have stated the problem is that gulp-uglifydoesn't support ES6. gulp-uglify-esdoes, however if is no longer maintained. Terseris recommended by others, but it doesn't play well with gulp and using it with pipe().

在让它工作之前,我在这方面工作了一段时间。正如其他答案所述,问题在于gulp-uglify不支持 ES6。gulp-uglify-es确实如此,但是 if 不再维护。Terser是其他人推荐的,但它与 gulp 和与pipe().

If you use gulp-uglifyas I do your gulpfile.jslooks something like:

如果你像我一样使用gulp-uglify,你gulpfile.js看起来像:

var uglify = require('gulp-uglify');
const html2js = () => {
     var source = gulp.src(config.appFiles.templates);
    return source
        .pipe(concat('templates-app.js'))
        .pipe(uglify())
        .pipe(gulp.dest(config.buildDir));
};

You can however use the gulp-terserpackage, which is very easy to just replace and get the same functionality:

但是,您可以使用gulp-terser包,它很容易替换并获得相同的功能:

var terser = require('gulp-terser');
const html2js = () => {
     var source = gulp.src(config.appFiles.templates);
    return source
        .pipe(concat('templates-app.js'))
        .pipe(terser())
        .pipe(gulp.dest(config.buildDir));
};

回答by Hitmands

unfortunately, as per now, you can't use uglifywith es-nextcode, you can:

不幸的是,现在每,你不能使用uglifyes-next代码,您可以:

  1. Transpile to ES5using Babel
  2. Use Babiliinstead of Uglify.
  1. 转译为ES5使用Babel
  2. 使用Babili而不是Uglify

回答by Giggs

module.exports = {
  ...
  optimization: {
    minimize: true
  },
  ...
}

webpack can do the job

webpack 可以完成这项工作