問題描述
當(dāng)我運(yùn)行 gulp 時(shí),我收到以下錯(cuò)誤:
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 }
違規(guī)行包含箭頭函數(shù):
let zeroCount = numberArray.filter(v => v === 0).length
我知道我可以將其替換為以下內(nèi)容,以通過放棄 ES6 語法來糾正縮小錯(cuò)誤:
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())
// [...]
});
這將在管道的早期轉(zhuǎn)譯您的 es6,并在您縮小時(shí)生成廣泛支持的純"javascript.
This will transpile your es6 early in the pipeline and churn out as widely supported "plain" javascript by the time you minify.
可能需要注意 - 正如評論中所指出的 - 核心 babel 編譯器作為 對等依賴 在這個(gè)插件中.如果核心庫沒有通過您的存儲庫中的另一個(gè) 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) 也可以使用.我的猜測是作者(這兩個(gè)項(xiàng)目都是一樣的)正在重新組織他們的模塊命名.無論哪種方式,兩個(gè) npm 安裝端點(diǎn)都指向 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
這篇關(guān)于如何使用 gulp-uglify 縮小 ES6 函數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!