我一定在某处犯了错误,但在优化期间它没有被写入标准输出。我正在尝试通过 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 包含所有其他模块。但是,它没有被缩小,并且没有一个变量被重命名。相反,就好像文件只是连接在一起,仅此而已。有人可以告诉我(1)为什么它没有被缩小? (2) UglifyJS 是否抛出错误?如果是这样,有没有办法在运行 gulp 任务时看到它?
编辑 这是 RequireJS 文档的链接,其中讨论了在节点中使用优化器,这是在上面提到的 gulp 任务中完成的。它位于“将优化器用作节点模块”下的底部。
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 只是跳过了该文件的缩小步骤。由于这不是一个彻底的错误,所以文件仍然是输出的,只是没有被缩小。
如果您更改
let
至var
在 myMod.js
,然后问题就消失了。不幸的是,由于这不是执行失败(
r.js
仍在运行,它只是不会缩小文件),因此不会向传递给 rjs.optimize
的 errback 处理程序发出错误信号。 .我看不到在 Gulpfile 中捕获此类错误的方法。安全的做法是设置 optimize: "none"
并在运行 rjs.optimize
后将缩小作为附加构建步骤执行.
关于gulp - RequireJS:丑化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373897/