Home Reference Source Test

source/utility.js

  1. import { cache, packageOf } from '@tech_query/node-toolkit';
  2.  
  3. import { JSDOM } from 'jsdom';
  4.  
  5. import { join } from 'path';
  6.  
  7. import { outputFile } from 'fs-extra';
  8.  
  9.  
  10. /**
  11. * @param {String} raw
  12. * @param {?Boolean} big - Big-camel style
  13. *
  14. * @return {String}
  15. */
  16. export function identifierOf(raw, big) {
  17.  
  18. raw = raw.replace(/\W+(\w)/g, (_, char) => char.toUpperCase())
  19. .replace(/^\d/, char => '_' + char);
  20.  
  21. return big ? (raw[0].toUpperCase() + raw.slice(1)) : raw;
  22. }
  23.  
  24.  
  25. /**
  26. * Get `package.json` data of `path` or `process.cwd()`
  27. *
  28. * @type {function(path: ?String): Object}
  29. */
  30. export const metaOf = cache(
  31. path => (packageOf(path || './test') || '').meta || { }
  32. );
  33.  
  34.  
  35. /**
  36. * Get `directories` field of `package.json` in `path` or `process.cwd()`
  37. *
  38. * @type {function(path: ?String): Object}
  39. */
  40. export const folderOf = cache(path => (metaOf(path) || '').directories || { });
  41.  
  42.  
  43. /**
  44. * @param {String} entry - Path of HTML file
  45. * @param {String} name - Tag name
  46. * @param {String} [base='dist/'] - Base path of JS files
  47. */
  48. export async function addComponent(entry, name, base) {
  49.  
  50. const page = await JSDOM.fromFile( entry );
  51.  
  52. const { document } = page.window;
  53.  
  54. const script = document.createElement('script');
  55.  
  56. script.setAttribute('src', join(base || 'dist', `${name}.js`));
  57.  
  58. document.head.append( script );
  59.  
  60. document.body.append( document.createElement( name ) );
  61.  
  62. await outputFile(entry, page.serialize());
  63. }