我尝试使用uglifyjs将javascript文件缩小为一个文件,但它无效。我使用$ node uglifyjs.js来运行该文件。以下是uglify.js中的代码
var fs = require('fs');
var uglifyjs = require('uglify-js');
var files = ['app.js', 'geolocation.service.js'];
var result = uglifyjs.minify(fs.readFileSync(files, 'utf8'));
console.log(result.code);
fs.writeFile("output.min.js", result.code, function(err){
if(err){
console.log(err);
} else {
console.log("File was successfully saved.");
}
});
当我运行此代码时,我收到以下错误消息:
fs.js:549
return binding.open(pathModule._makeLong(path), stringToFlags(flags),
mode);
^
TypeError: path must be a string
at TypeError (native)
at Object.fs.openSync (fs.js:549:18)
at Object.fs.readFileSync (fs.js:397:15)
at Object.<anonymous> (C:\Users\HP\Desktop\uglify\uglify.js:7:33)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
答案 0 :(得分:4)
如here所示,uglify.minify
要求您传递string
或string
个列表。
您的代码:
var result = uglifyjs.minify(fs.readFileSync(files, 'utf8'));
尝试一次读取多个文件,但fs.readFileSync
只接受一个文件。
所以将代码更改为:
var filesContents = ['app.js', 'geolocation.service.js'].map(function (file) {
return fs.readFileSync(file, 'utf8');
})
var result = uglifyjs.minify(filesContents);
if (result.error) {
console.error("Error minifying: " + result.error);
}
fs.writeFile("output.min.js", result.code, function (err) {
if (err) {
console.error(err);
} else {
console.log("File was successfully saved.");
}
});