Node. js implements the JS file merge gadget

  • 2020-12-10 00:38:44
  • OfStack

Near the Spring Festival, the end of the project, there is nothing to do, so I want to learn node.js, before I wrote 1 is for the needs of the laboratory project, c# wrote an js code compression and combination of small plug-ins, then I thought that you can use node refactoring, so practice your hands, the following site directly to you on the code.

The code is as follows:


/* Conform to the CommonJs specification */
var writePath = 'min.js',/* Default output to this directory min.js In the file */
fs = require('fs'),
r1 = /^(.+)$/mg,/* branch */
r2 = /\s{2,}/g,/* Go to the space */
r3 = /([^\\])\/\/.*/g,/* To comment */
r4 = /\/\*.*?\*\//g,/* To block comment */
str = '';
module.exports.run = function(input){
input.forEach(function(item){
/* Merges require order, so read files synchronously */
var data = fs.readFileSync(item, 'utf8'),
lines = data.match(r1);/* Line array */
/* Mosaic 1 string */
lines.forEach(function(item){
item = item.replace(r3, function($1, $2){return $2;});
str = str + item;
});
});
str = str.replace(r2,' ').replace(r4, ''); 
/* Writes asynchronously to the target file */
fs.appendFile(writePath, str, {encoding: 'utf8'}, function(err){
if(err) {throw err};
console.log('complete........');
});
}; 

Although the content is small, but still want to adapt to 1 commomJS's modular programming, so it separated the above module ^_^, file name: compress.js.

Here's the code that references it:


var a = require('./compress.js');/* loading compress The module   ' ./' Looks for local files in the same directory */
var input = process.argv;/* Gets the console input array ( process Referring to the current process */
a.run(input.slice(2)/* Ignore the first two of the first array */); 

run. js

Console operation:

$ node run a.js b.js c.js....

You can compress a.js b.js c.js (relative path, or absolute path, path positioning similar to other languages) into the default min.js.

Of course, this compression is not perfect, the space is not complete enough, there is no stream-based (JS files are not too big), and professional compression plug-ins such as ES45en.js can not compare with the others.


Related articles: