Home > Web Front-end > JS Tutorial > A simple project packaging tool written in nodejs_json

A simple project packaging tool written in nodejs_json

WBOY
Release: 2016-05-16 17:34:07
Original
1343 people have browsed it

The module loading and definition part of the project code is as follows:

Copy code The code is as follows:

XX.define('ns',['tool/ cookie'],function(){
});
//or
XX.define('ns.ns2','tool/cookie,tool/abc',function(){
})
//or
XX.define('ns',function(){
})

The js packaging tool used is to scan the file, then match the modules that need to be loaded, and then load the module code first.
The main nodejs packaging tool code is as follows:

Copy code The code is as follows:

//通用模块
var Util = require('util'),
    FS = require('fs'),
    getDeps = require('./getDeps'),
    Uglify = require('./uglify/uglify-js'),
    removeBOMChar = require('./removeBOM').removeBOMChar,
    PATH =require('path');

var packagedObj = {};//是否已经打包过

module.exports = function(filePath, rootPath, opts){
    opts = opts || {};

    var str = jscombo(filePath,rootPath);
    if(opts.unzip){
        return str;
    }else{
        return Uglify(str);  
    }
};

function jscombo(filePaths, rootPath){
    if(Util.isArray(filePaths)){
        return filePaths.map(function(filePath){           
            filePath = PATH.join(rootPath,filePath);

            //只打包一次
            if(packagedObj[filePath]){
                return '';
            }
            packagedObj[filePath] = 1;

            //是否存在
            if(FS.existsSync(filePath)){
                //异步读取内容
                var str = FS.readFileSync(filePath, 'utf-8');
                //移出BOM头
                str = removeBOMChar(str);
                var result = getDeps(str, rootPath);
                var content = result.content;
                content = '//' filePath 'n' content;

                //递归打包
                if(result.list){
                    return jscombo(result.list, rootPath) content;
                }               
                //返回内容
                return content;
            }else{
                //文件不存在错误信息
                console.error('jsCombo Error: ' filePath ' does not exsist! the path is:' rootPath);
                return ';alert("' filePath ' does not exsist!");';
            }           
        }).join(';n');

    }else{
        return jscombo([filePaths],rootPath);
    }
}

对于nodejs之前一直没认真学习,都是边查文档,编写的,所以代码很青涩~

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template