您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

329 行
8.3 KiB

  1. /*eslint-disable no-console */
  2. const path = require('path');
  3. const fs = require('fs');
  4. const babel = require('babel-core');
  5. const less = require('less');
  6. const chokidar = require('chokidar');
  7. const path_join = path.resolve;
  8. // for file watcher
  9. const app = require('express')();
  10. const http = require('http').Server(app);
  11. const io = require('socket.io')(http);
  12. const touch = require("touch");
  13. // basic setup
  14. const sites_path = path_join(__dirname, '..', '..', '..', 'sites');
  15. const apps_path = path_join(__dirname, '..', '..', '..', 'apps'); // the apps folder
  16. const apps_contents = fs.readFileSync(path_join(sites_path, 'apps.txt'), 'utf8');
  17. const apps = apps_contents.split('\n');
  18. const app_paths = apps.map(app => path_join(apps_path, app, app)) // base_path of each app
  19. const assets_path = path_join(sites_path, 'assets');
  20. let build_map = make_build_map();
  21. const file_watcher_port = get_conf().file_watcher_port;
  22. // command line args
  23. const action = process.argv[2] || '--build';
  24. if (['--build', '--watch'].indexOf(action) === -1) {
  25. console.log('Invalid argument: ', action);
  26. process.exit();
  27. }
  28. if (action === '--build') {
  29. const minify = process.argv[3] === '--minify' ? true : false;
  30. build(minify);
  31. }
  32. if (action === '--watch') {
  33. watch();
  34. }
  35. function build(minify) {
  36. for (const output_path in build_map) {
  37. pack(output_path, build_map[output_path], minify);
  38. }
  39. touch(path_join(sites_path, '.build'), {force:true});
  40. }
  41. let socket_connection = false;
  42. function watch() {
  43. http.listen(file_watcher_port, function () {
  44. console.log('file watching on *:', file_watcher_port);
  45. });
  46. compile_less().then(() => {
  47. build();
  48. watch_less(function (filename) {
  49. if(socket_connection) {
  50. io.emit('reload_css', filename);
  51. }
  52. });
  53. // watch_js(function (filename) {
  54. // if(socket_connection) {
  55. // io.emit('reload_js', filename);
  56. // }
  57. // });
  58. watch_build_json();
  59. });
  60. io.on('connection', function (socket) {
  61. socket_connection = true;
  62. socket.on('disconnect', function() {
  63. socket_connection = false;
  64. })
  65. });
  66. }
  67. function pack(output_path, inputs, minify) {
  68. const output_type = output_path.split('.').pop();
  69. let output_txt = '';
  70. for (const file of inputs) {
  71. if (!fs.existsSync(file)) {
  72. console.log('File not found: ', file);
  73. continue;
  74. }
  75. let file_content = fs.readFileSync(file, 'utf-8');
  76. if (file.endsWith('.html') && output_type === 'js') {
  77. file_content = html_to_js_template(file, file_content);
  78. }
  79. if(file.endsWith('class.js')) {
  80. file_content = minify_js(file_content, file);
  81. }
  82. if (file.endsWith('.js') && !file.includes('/lib/') && output_type === 'js' && !file.endsWith('class.js')) {
  83. file_content = babelify(file_content, file, minify);
  84. }
  85. if(!minify) {
  86. output_txt += `\n/*\n *\t${file}\n */\n`
  87. }
  88. output_txt += file_content;
  89. output_txt = output_txt.replace(/['"]use strict['"];/, '');
  90. }
  91. const target = path_join(assets_path, output_path);
  92. try {
  93. fs.writeFileSync(target, output_txt);
  94. console.log(`Wrote ${output_path} - ${get_file_size(target)}`);
  95. return target;
  96. } catch (e) {
  97. console.log('Error writing to file', output_path);
  98. console.log(e);
  99. }
  100. }
  101. function babelify(content, path, minify) {
  102. let presets = ['env'];
  103. // Minification doesn't work when loading Frappe Desk
  104. // Avoid for now, trace the error and come back.
  105. try {
  106. return babel.transform(content, {
  107. presets: presets,
  108. comments: false
  109. }).code;
  110. } catch (e) {
  111. console.log('Cannot babelify', path);
  112. console.log(e);
  113. return content;
  114. }
  115. }
  116. function minify_js(content, path) {
  117. try {
  118. return babel.transform(content, {
  119. comments: false
  120. }).code;
  121. } catch (e) {
  122. console.log('Cannot minify', path);
  123. console.log(e);
  124. return content;
  125. }
  126. }
  127. function make_build_map() {
  128. const build_map = {};
  129. for (const app_path of app_paths) {
  130. const build_json_path = path_join(app_path, 'public', 'build.json');
  131. if (!fs.existsSync(build_json_path)) continue;
  132. let build_json = fs.readFileSync(build_json_path);
  133. try {
  134. build_json = JSON.parse(build_json);
  135. } catch (e) {
  136. console.log(e);
  137. continue;
  138. }
  139. for (const target in build_json) {
  140. const sources = build_json[target];
  141. const new_sources = [];
  142. for (const source of sources) {
  143. const s = path_join(app_path, source);
  144. new_sources.push(s);
  145. }
  146. if (new_sources.length)
  147. build_json[target] = new_sources;
  148. else
  149. delete build_json[target];
  150. }
  151. Object.assign(build_map, build_json);
  152. }
  153. return build_map;
  154. }
  155. function compile_less() {
  156. return new Promise(function (resolve) {
  157. const promises = [];
  158. for (const app_path of app_paths) {
  159. const public_path = path_join(app_path, 'public');
  160. const less_path = path_join(public_path, 'less');
  161. if (!fs.existsSync(less_path)) continue;
  162. const files = fs.readdirSync(less_path);
  163. for (const file of files) {
  164. if(file.includes('variables.less')) continue;
  165. promises.push(compile_less_file(file, less_path, public_path))
  166. }
  167. }
  168. Promise.all(promises).then(() => {
  169. console.log('Less files compiled');
  170. resolve();
  171. });
  172. });
  173. }
  174. function compile_less_file(file, less_path, public_path) {
  175. const file_content = fs.readFileSync(path_join(less_path, file), 'utf8');
  176. const output_file = file.split('.')[0] + '.css';
  177. console.log('compiling', file);
  178. return less.render(file_content, {
  179. paths: [less_path],
  180. filename: file,
  181. sourceMap: false
  182. }).then(output => {
  183. const out_css = path_join(public_path, 'css', output_file);
  184. fs.writeFileSync(out_css, output.css);
  185. return out_css;
  186. }).catch(e => {
  187. console.log('Error compiling ', file);
  188. console.log(e);
  189. });
  190. }
  191. function watch_less(ondirty) {
  192. const less_paths = app_paths.map(path => path_join(path, 'public', 'less'));
  193. const to_watch = filter_valid_paths(less_paths);
  194. chokidar.watch(to_watch).on('change', (filename) => {
  195. console.log(filename, 'dirty');
  196. var last_index = filename.lastIndexOf('/');
  197. const less_path = filename.slice(0, last_index);
  198. const public_path = path_join(less_path, '..');
  199. filename = filename.split('/').pop();
  200. compile_less_file(filename, less_path, public_path)
  201. .then(css_file_path => {
  202. // build the target css file for which this css file is input
  203. for (const target in build_map) {
  204. const sources = build_map[target];
  205. if (sources.includes(css_file_path)) {
  206. pack(target, sources);
  207. ondirty && ondirty(target);
  208. break;
  209. }
  210. }
  211. });
  212. touch(path_join(sites_path, '.build'), {force:true});
  213. });
  214. }
  215. function watch_js(ondirty) {
  216. const js_paths = app_paths.map(path => path_join(path, 'public', 'js'));
  217. const to_watch = filter_valid_paths(js_paths);
  218. chokidar.watch(to_watch).on('change', (filename, stats) => {
  219. console.log(filename, 'dirty');
  220. // build the target js file for which this js/html file is input
  221. for (const target in build_map) {
  222. const sources = build_map[target];
  223. if (sources.includes(filename)) {
  224. pack(target, sources);
  225. ondirty && ondirty(target);
  226. // break;
  227. }
  228. }
  229. touch(path_join(sites_path, '.build'), {force:true});
  230. });
  231. }
  232. function watch_build_json() {
  233. const build_json_paths = app_paths.map(path => path_join(path, 'public', 'build.json'));
  234. const to_watch = filter_valid_paths(build_json_paths);
  235. chokidar.watch(to_watch).on('change', (filename) => {
  236. console.log(filename, 'updated');
  237. build_map = make_build_map();
  238. });
  239. }
  240. function filter_valid_paths(paths) {
  241. return paths.filter(path => fs.existsSync(path));
  242. }
  243. function html_to_js_template(path, content) {
  244. let key = path.split('/');
  245. key = key[key.length - 1];
  246. key = key.split('.')[0];
  247. content = scrub_html_template(content);
  248. return `frappe.templates['${key}'] = '${content}';\n`;
  249. }
  250. function scrub_html_template(content) {
  251. content = content.replace(/\s/g, ' ');
  252. content = content.replace(/(<!--.*?-->)/g, '');
  253. return content.replace("'", "\'");
  254. }
  255. function get_file_size(filepath) {
  256. const stats = fs.statSync(filepath);
  257. const size = stats.size;
  258. // convert it to humanly readable format.
  259. const i = Math.floor(Math.log(size) / Math.log(1024));
  260. return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
  261. }
  262. function get_conf() {
  263. // defaults
  264. var conf = {
  265. file_watcher_port: 6787
  266. };
  267. var read_config = function(path) {
  268. if (!fs.existsSync(path)) return;
  269. var bench_config = JSON.parse(fs.readFileSync(path));
  270. for (var key in bench_config) {
  271. if (bench_config[key]) {
  272. conf[key] = bench_config[key];
  273. }
  274. }
  275. }
  276. read_config(path_join(sites_path, 'common_site_config.json'));
  277. return conf;
  278. }