grunt-commonizor
Version:
plugin for building js file to support commonjs
127 lines (100 loc) • 3.63 kB
JavaScript
/*
* grunt-commonizor
* wrap jsfiles to support commonjs.
*
* Copyright (c) 2015 大法
* Licensed under the MIT license.
*/
/**
* 输出文件名:
* 按src文件名xxx.js转为对应的xxx.js
*
* 模块输出(module.exports):
* 只有pkg名字和文件名一致的文件才会将模块用module.exports输出
* 其他可以自行通过挂载到windows上的变量存取
*/
;
var path = require('path'),
grunt,
pkg, // package
modPkgFile = function(files, pkg, options) {
var src = files[0].src[0],
ext = 'common.js',
dependencies = pkg.dependencies,
name = pkg.name;
grunt.log.debug('commonizor: add commonjs support for ' + name);
if (name !== 'grunt-commonizor') {
if (!pkg.main) {
pkg.main = 'build/' + name + '.' + ext;
}
//////// 更新package.json文件
grunt.file.write('package.json', JSON.stringify(pkg, null, 2));
grunt.log.writeln('finished writing to package.json.');
}
},
getJsRequiresFromDeps = function(deps) {
//////// 添加deps里的依赖组件到requires里
var requires;
if (deps) {
requires = Object.keys(deps).map(function(key) {
return "'" + key + "'";
});
} else {
requires = [];
}
return requires;
},
wrapWithCommonJs = function(requires, options, file) {
//////// 合并多个源文件并打包输出commonjs文件
var dest = file.dest,
style = file.dest,
name = pkg.name;
if (file.src && file.src.length > 0) {
grunt.log.debug('commonizor: src - ' + file.src);
var jsFile = '';
//////// 拼接require依赖声明
jsFile += '(typeof window === \'undefined\') && (window = {ctrl: {}, lib: {}});!window.ctrl && (window.ctrl = {});!window.lib && (window.lib = {});';
for (var i = 0, l = requires.length; i < l; i++) {
jsFile += 'require(' + requires[i] + ');';
}
//////// 拼接多个源文件
file.src.forEach(function(f, idx) {
var src = f;
grunt.log.debug('commonizor: handleing with file \'' + src + '\'');
if (!src.match(/\.js$/)) {
grunt.fail.fatal('Source file must be a js file.');
}
jsFile += grunt.file.read(src);
});
file.src.forEach(function(f, idx) {
if (name === path.basename(f, '.js')) {
// 如果是组件的主文件则通过module.exports输出
// 如果有type则输出的是window[type][name],如果没有则输出的是window[name]
jsFile += ';module.exports = window.lib' + '[\'' + name + '\'];';
}
});
grunt.log.debug('commonizor: saving file - ' + dest);
grunt.file.write(dest, jsFile);
grunt.log.writeln('File "' + dest + '" created.');
} else {
grunt.fail.fatal('Source file "' + file.orig.src + '" not found.');
}
};
module.exports = function(gt) {
grunt = gt;
grunt.registerMultiTask('commonizor', 'Wrap File for CommonJS', function() {
var options = this.options({}),
packageFile = options.pkg || grunt.file.readJSON('package.json'),
dependencies = packageFile.dependencies,
requires; // 依赖到的文件相对路径的缓存
pkg = packageFile;
if (!pkg) {
return grunt.log.error('specific "pkg" field in options');
}
requires = getJsRequiresFromDeps(dependencies);
// Iterate over all specified file groups.
this.files.forEach(wrapWithCommonJs.bind({}, requires, options));
///////// 将部分信息写入package.json中
modPkgFile(this.files, pkg, options);
});
};