js.js 953 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const { htmlTag, url_for } = require('hexo-util');
  3. /* flatten() to be replaced by Array.flat()
  4. after Node 10 has reached EOL */
  5. const flatten = function(arr, result = []) {
  6. for (const i in arr) {
  7. const value = arr[i];
  8. if (Array.isArray(value)) {
  9. flatten(value, result);
  10. } else {
  11. result.push(value);
  12. }
  13. }
  14. return result;
  15. };
  16. function jsHelper(...args) {
  17. let result = '\n';
  18. flatten(args).forEach(item => {
  19. // Old syntax
  20. if (typeof item === 'string' || item instanceof String) {
  21. let path = item;
  22. if (!path.endsWith('.js')) {
  23. path += '.js';
  24. }
  25. result += `<script src="${url_for.call(this, path)}"></script>\n`;
  26. } else {
  27. // New syntax
  28. item.src = url_for.call(this, item.src);
  29. if (!item.src.endsWith('.js')) item.src += '.js';
  30. result += htmlTag('script', { ...item }, '') + '\n';
  31. }
  32. });
  33. return result;
  34. }
  35. module.exports = jsHelper;