dependence.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * grunt-module-dependence
  3. * https://github.com/HanCong03/formula
  4. *
  5. * Copyright (c) 2014 hancong03
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. module.exports = function (grunt) {
  10. var PathModule = require("path"),
  11. UglifyJS = require("uglify-js");
  12. // 依赖池名称
  13. var depsPoolName = null,
  14. // 名称装饰后的映射表
  15. moduleMapping = {},
  16. idMapping = {},
  17. moudeIndex = 0;
  18. grunt.registerMultiTask('dependence', 'The best Grunt plugin ever.', function () {
  19. // 已处理后的module源码
  20. var transformedSource = null;
  21. var filenameList = [];
  22. var options = this.options({
  23. base: './',
  24. entrance: null,
  25. separator: '\n'
  26. }),
  27. moduleBase = PathModule.resolve(options.base) + PathModule.sep;
  28. initDepsPool();
  29. resetModuleIndex();
  30. this.files.forEach(function (fileConfig) {
  31. transformedSource = [];
  32. fileConfig.src.filter(function (filepath) {
  33. var source = null,
  34. currentModuleName = null;
  35. if (!grunt.file.exists(filepath)) {
  36. grunt.log.warn('Source file "' + filepath + '" not found.');
  37. return false;
  38. } else {
  39. source = '//' + filepath + '\n' + grunt.file.read(filepath);
  40. currentModuleName = getModuleName(filepath, source);
  41. if (currentModuleName.type === "id") {
  42. idMapping[currentModuleName.value] = moudeIndex;
  43. } else {
  44. moduleMapping[currentModuleName.value] = moudeIndex;
  45. }
  46. transformedSource.push(transform(moudeIndex, source));
  47. filenameList[moudeIndex] = currentModuleName.path;
  48. moudeIndex++;
  49. return true;
  50. }
  51. });
  52. for (var i = 0, len = transformedSource.length; i < len; i++) {
  53. transformedSource[i] = removeRequire(filenameList[i], transformedSource[i], moduleBase);
  54. }
  55. // 合并源码
  56. transformedSource = transformedSource.join( options.separator );
  57. transformedSource = wrap(transformedSource, options);
  58. transformedSource = format(transformedSource);
  59. grunt.file.write(fileConfig.dest, transformedSource);
  60. grunt.log.writeln('Concated ' + (moudeIndex).toString().cyan + ' Modules, File "' + fileConfig.dest + '" created.');
  61. });
  62. });
  63. /**
  64. * 根据给定的base目录和module路径以及源码获取格式化后的modulePath
  65. */
  66. function getModuleName(filepath, source) {
  67. filepath = PathModule.resolve(filepath);
  68. if (/\bdefine\s*\(\s*("|')([\s\S]+?)\1\s*,\s*/g.test(source)) {
  69. return {
  70. type: "id",
  71. value: RegExp.$2,
  72. path: filepath
  73. };
  74. }
  75. return {
  76. type: "path",
  77. value: PathModule.resolve(filepath),
  78. path: filepath
  79. };
  80. }
  81. /**
  82. * 初始化依赖池名称
  83. */
  84. function initDepsPool() {
  85. depsPoolName = '_p';
  86. }
  87. function resetModuleIndex() {
  88. moudeIndex = 0;
  89. }
  90. /**
  91. * 对module执行转换,更改其定义方式,使其可以脱离define方法
  92. * @param source
  93. */
  94. function transform(index, source) {
  95. var prefix = depsPoolName + "[" + index + "]",
  96. pattern = /(?:\/\*(?:[\s\S](?!\*\/))*?[\s\S]?\*\/\s*$)|(?:\/\/[^\n]*\s*$)/,
  97. lastIndex = -1,
  98. tailSource = null,
  99. tmpSource = null,
  100. match = null;
  101. source = source.replace(/\bdefine\s*\(\s*(?:("|')([\s\S]+?)\1\s*,\s*)?/g, prefix + "={\nvalue: ");
  102. tmpSource = source;
  103. while (pattern.test(tmpSource)) {
  104. tmpSource = tmpSource.replace(pattern, '');
  105. }
  106. lastIndex = tmpSource.lastIndexOf(')');
  107. tailSource = source.substring(lastIndex);
  108. source = source.substring(0, lastIndex);
  109. return source + tailSource.replace(/\)\s*;?/, '};');
  110. }
  111. /**
  112. * 删除require依赖
  113. */
  114. function removeRequire(filepath, source, moduleBase) {
  115. try {
  116. return source.replace(/\brequire\s*\(\s*("|')([\s\S]*?)\1\s*\)/g, function (match, sign, moduleName) {
  117. var originalName = moduleName;
  118. if (/^[.]{1,2}\//.test(moduleName)) {
  119. moduleName = PathModule.resolve(PathModule.dirname(filepath) + PathModule.sep + moduleName);
  120. } else if (idMapping.hasOwnProperty(moduleName)) {
  121. return depsPoolName + '.r(' + idMapping[moduleName] + ')';
  122. } else {
  123. moduleName = PathModule.resolve(moduleBase + moduleName);
  124. }
  125. if (PathModule.extname(moduleName) === "") {
  126. moduleName += ".js";
  127. }
  128. if (moduleMapping.hasOwnProperty(moduleName)) {
  129. return depsPoolName + ".r(" + moduleMapping[moduleName] + ")";
  130. }
  131. throw new ModuleNotfoundError(originalName);
  132. });
  133. } catch (e) {
  134. if (e.name === "ModuleNotfoundError") {
  135. grunt.fatal('Module [' + e.message + '] not found, in file: ' + filepath);
  136. }
  137. throw e;
  138. }
  139. }
  140. /**
  141. * 格式化源码
  142. * @param source
  143. */
  144. function format(source) {
  145. var ast = UglifyJS.parse(source);
  146. return ast.print_to_string({
  147. beautify: true,
  148. comments: 'all'
  149. });
  150. }
  151. /**
  152. * 包裹最终的源码
  153. * @param source
  154. */
  155. function wrap(source, options) {
  156. return getWrapTpl().replace(/^function\s*\(\s*\)\s*\{|\}\s*$/gi, '')
  157. .replace(/\$name/g, depsPoolName)
  158. .replace('$source;', source) + '\n' + getUseTpl(options.entrance);
  159. }
  160. /*-------------- 获取包裹函数模板*/
  161. function getWrapTpl() {
  162. return function () {
  163. var $name = {
  164. r: function (index) {
  165. if ($name[index].inited) {
  166. return $name[index].value;
  167. }
  168. if (typeof $name[index].value === 'function') {
  169. var module = {
  170. exports: {}
  171. },
  172. returnValue = $name[index].value(null, module.exports, module);
  173. $name[index].inited = true;
  174. $name[index].value = returnValue;
  175. if (returnValue !== undefined) {
  176. return returnValue;
  177. } else {
  178. for (var key in module.exports) {
  179. if (module.exports.hasOwnProperty(key)) {
  180. $name[index].inited = true;
  181. $name[index].value = module.exports;
  182. return module.exports;
  183. }
  184. }
  185. }
  186. } else {
  187. $name[index].inited = true;
  188. return $name[index].value;
  189. }
  190. }
  191. };
  192. $source;
  193. }.toString();
  194. }
  195. /**
  196. * Use函数入口
  197. * @param entrance
  198. */
  199. function getUseTpl(entrance) {
  200. var entranceMap = null,
  201. tmp = {},
  202. entranceName = entrance;
  203. if (entrance) {
  204. if (moduleMapping.hasOwnProperty(entrance)) {
  205. entrance = moduleMapping[entrance];
  206. } else if (idMapping.hasOwnProperty(entrance)) {
  207. entrance = idMapping[entrance];
  208. } else {
  209. entrance = null;
  210. }
  211. }
  212. if (!isNumber(entrance)) {
  213. entranceMap = 'var moduleMapping = ' + JSON.stringify(moduleMapping) + ';';
  214. } else {
  215. tmp[entranceName] = entrance;
  216. entranceMap = 'var moduleMapping = ' + JSON.stringify(tmp) + ';';
  217. }
  218. return entranceMap + '\nfunction use (name) {' + depsPoolName + '.r([moduleMapping[name]]);}';
  219. }
  220. function isNumber(val) {
  221. return typeof val === "number";
  222. }
  223. /*----------- 自定义错误类*/
  224. function ModuleNotfoundError(message) {
  225. this.message = message;
  226. this.name = 'ModuleNotfoundError';
  227. }
  228. ModuleNotfoundError.prototype = new Error();
  229. };