RequireJS:丑化不起作用

RequireJS: Uglification Not Working

我一定是哪里出错了,但在优化期间没有写入标准输出。我正在尝试通过 requirejs 优化文件,但输出没有被缩小。根据 documentation,UglifyJS 应该缩小代码。

无论如何,下面的代码很简单,但它隔离了问题。

src/index.js:

require(['config'], function () {
    require(['myMod'], function (myMod) {
        console.log(myMod.x());
    })
})

src/myMod.js:

define(function () {
    let myMod = {
        x: 5
    };

    return myMod;
})

src/config.js:

define(function () {
    require.config({
        baseUrl: 'src'
    });
})

这是执行优化的 gulp 任务:

gulp.task('optimize', function (cb) {
    let config = {
        appDir: 'src',
        dir: 'dist/src',
        generateSourceMaps: true,
        preserveLicenseComments: false,
        removeCombined: true,
        baseUrl: './',
        modules: [{
            name: 'index',
            include: ['myMod']
        }]
    }

    let success = function (buildResponse) { console.log(buildResponse); cb() },
        error = function (err) { console.log(err); cb(err) }

    rjs.optimize(config, success, error)
})

在 运行 完成任务后,dist/src/index.js 包含所有其他模块。但是,它没有缩小,并且 none 的变量已重命名。相反,就好像文件只是串联在一起,仅此而已。有人能告诉我(1)为什么它没有被缩小吗? (2) UglifyJS 是否抛出错误?如果是这样,有没有办法在 gulp 任务 运行 时看到它?

编辑 这是 RequireJS 文档的 link,其中讨论了在节点中使用优化器,这是在上面提到的 gulp 任务中完成的。它位于 "Using the optimizer as a node module".

下方的底部

http://requirejs.org/docs/node.html

RequireJS 的优化器捆绑了 UglifyJS2。 UglifyJS2 不处理 ES6 或更高版本。如果我采用您在 gulpfile 中使用的选项,并将它们放入一个我命名为 options.js 的单独文件中,然后发出此命令:

$ ./node_modules/.bin/r.js -o options.js

然后我得到这个输出:

Tracing dependencies for: index
Uglify file: /tmp/t33/dist/src/index.js
Error: Cannot uglify file: /tmp/t33/dist/src/index.js. Skipping it. Error is:
SyntaxError: Unexpected token: name (myMod)

If the source uses ES2015 or later syntax, please pass "optimize: 'none'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.

index.js
----------------
config.js
index.js
myMod.js

如您所见,UglifyJS 确实无法缩小您的文件,而 RequireJS 只是跳过该文件的缩小步骤。由于这不是一个彻底的错误,文件仍然会输出,只是没有缩小。

如果您在 myMod.js 中将 let 更改为 var,那么问题就会消失。

不幸的是,由于这不是执行失败(r.js 仍在运行,它只是没有缩小文件),因此不会向传递给 rjs.optimize 的 errback 处理程序发出错误信号。我没有看到在 Gulpfile 中捕获此类错误的方法。安全的做法是设置 optimize: "none" 并在 运行 rjs.optimize.

之后执行缩小作为附加构建步骤

我也 运行 遇到了同样的问题,其中 require.js 的优化器 (r.js) 正在组合不同的模块,但是,它没有缩小合并的文件。尽管我的 运行 时间环境与您的不同(使用 Java 的 Nashorn 引擎),但在我的控制台上可以看到此错误:

If the source uses ES2015 or later syntax, please pass "optimize: 'none'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax. 

此外,此错误不会阻止优化器合并文件,只是优化器将无法缩小合并后的文件。