UglifyJS抛出意外的令牌:关键字(const)和node_modules [英] UglifyJS throws unexpected token: keyword (const) with node_modules
问题描述
我开始的一个小项目使用一个节点模块(通过 npm 安装)来声明 const
变量。运行和测试这个项目很好,但是当执行UglifyJS时,browserify失败。
A small project I started make use a node module (installed via npm) that declares const
variables. Running and testing this project is well, but browserify fails when UglifyJS is executed.
意外的令牌:关键字(const)
Unexpected token: keyword (const)
这是一个通用的Gulp文件,我已经成功地用于其他一些过去没有这个问题的项目(即没有那个特定的节点模块)。
Here is a generic Gulp file that I have successfully been using for a few other past projects without this issue (i.e. without that particular node module).
'use strict';
const browserify = require('browserify');
const gulp = require('gulp');
const source = require('vinyl-source-stream');
const derequire = require('gulp-derequire');
const buffer = require('vinyl-buffer');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const gutil = require('gulp-util');
const path = require('path');
const pkg = require('./package');
const upperCamelCase = require('uppercamelcase');
const SRC_PATH = path.dirname(pkg.main);
const DIST_PATH = path.dirname(pkg.browser);
const INPUT_FILE = path.basename(pkg.main);
const OUTPUT_FILE = path.basename(pkg.browser);
const MODULE_NAME = upperCamelCase(pkg.name);
gulp.task('default', () => {
// set up the browserify instance on a task basis
var b = browserify({
entries: INPUT_FILE,
basedir: SRC_PATH,
transform: ['babelify'],
standalone: MODULE_NAME,
debug: true
});
return b.bundle()
.pipe(source(OUTPUT_FILE))
.pipe(buffer())
.pipe(derequire())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(DIST_PATH))
;
});
我试过通过替换所有 const
在npm-installed模块中输入 var
,一切都很好。所以我不明白失败。
I have tried fixing this by replace all const
to var
in that npm-installed module, and everything is fine. So I do not understand the failure.
const
有什么问题?除非有人使用IE10,所有主流浏览器都支持这种语法。
What's wrong with const
? Unless someone uses IE10, all major browsers support this syntax.
有没有办法解决这个问题,而无需更改该节点模块?
Is there a way to fix this without requiring a change to that node module?
我暂时(或永久)用 Butternut 并且似乎有效。
I have temporarily (or permanently) replaced UglifyJS with Butternut and seem to work.
推荐答案
2018年11月更新:
使用 terser-webpack-plugin (webpack @ 5将使用此插件进行uglification)
Use terser-webpack-plugin for ES6 (webpack@5 will use this plugin for uglification)
npm install terser-webpack-plugin --save-dev
然后在你的<$中定义c $ c> plugins array
Then define in your plugins
array
const TerserPlugin = require('terser-webpack-plugin')
new TerserPlugin({
parallel: true,
terserOptions: {
ecma: 6,
},
}),
这篇关于UglifyJS抛出意外的令牌:关键字(const)和node_modules的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!