Home Reference Source Test

source/command.js

  1. import { join, basename } from 'path';
  2.  
  3. import {outputFile, existsSync, statSync, readdir} from 'fs-extra';
  4.  
  5. import Component from './Component';
  6.  
  7. import { index_html, index_js, router_js } from './template';
  8.  
  9. import { addComponent } from './utility';
  10.  
  11.  
  12. /**
  13. * @param {String} name - Tag name
  14. * @param {String} path - Root of Source codes
  15. * @param {String[]} [keys=[]] - Defined HTML attributes
  16. * @param {?Boolean} preload - Insert Component tag to Entry HTML
  17. */
  18. export async function createCell(name, path, keys, preload) {
  19.  
  20. await outputFile(join(path, name, 'index.html'), index_html());
  21.  
  22. console.info(`√ Generated ${name}/index.html`);
  23.  
  24. await outputFile(join(path, name, 'index.js'), index_js(name, keys));
  25.  
  26. console.info(`√ Generated ${name}/index.js`);
  27.  
  28. if ( preload ) await addComponent(join(path, '../index.html'), name);
  29. }
  30.  
  31.  
  32. /**
  33. * @param {String} name - Prefix of Tag name
  34. * @param {String} path - Root of Source codes
  35. * @param {String[]} [page=[]] - Router/Page names of Web-site/app
  36. */
  37. export async function createRouter(name, path, page) {
  38.  
  39. const tag = `${name}-router`;
  40.  
  41. await outputFile(join(path, tag, 'index.js'), router_js(name, page));
  42.  
  43. console.info(`√ Generated ${tag}/index.js`);
  44.  
  45. await addComponent(join(path, '../index.html'), tag);
  46.  
  47. for (let name of page) await createCell(`page-${name}`, path);
  48. }
  49.  
  50.  
  51. /**
  52. * Bundle components to JS modules
  53. *
  54. * @param {string} path - Source directory
  55. *
  56. * @return {string[]} Component paths
  57. */
  58. export async function bundle(path) {
  59.  
  60. var result = [ ];
  61.  
  62. if (existsSync( join(path, 'index.js') )) {
  63.  
  64. const component = new Component( path );
  65.  
  66. result[0] = `dist/${component.name}.js`;
  67.  
  68. await outputFile(result[0], await component.toJS());
  69. }
  70.  
  71. if (statSync( path ).isDirectory())
  72. result = result.concat(... await Promise.all(
  73. (await readdir( path )).map(file => bundle( join(path, file) ))
  74. ));
  75.  
  76. return result;
  77. }
  78.  
  79.  
  80. /**
  81. * Bundle components into a JS package
  82. *
  83. * @param {string} path - Source directory
  84. *
  85. * @return {string[]} Component paths
  86. */
  87. export async function pack(path) {
  88.  
  89. const file = await bundle( path );
  90.  
  91. await outputFile(
  92. 'dist/index.js',
  93. file.map(item => {
  94.  
  95. item = basename( item );
  96.  
  97. console.info(`√ Component "${item}" is packed in`);
  98.  
  99. return `export * from './${item}';`;
  100.  
  101. }).join('\n')
  102. );
  103.  
  104. return file;
  105. }