loader.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var fs = require('fs');
  2. var crypto = require('crypto');
  3. const getParams = query => {
  4. if (!query) {
  5. return { };
  6. }
  7. return (/^[?#]/.test(query) ? query.slice(1) : query)
  8. .split('&')
  9. .reduce((params, param) => {
  10. let [ key, value ] = param.split('=');
  11. params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
  12. return params;
  13. }, { });
  14. };
  15. module.exports = function(source) {
  16. const params = getParams(this.query);
  17. const chunk = crypto.createHash('md5').update(this.resource).digest("hex");
  18. if (params.path === undefined) {
  19. this.emitError('path parameter must be provided');
  20. }
  21. if(this.cacheable) this.cacheable();
  22. const regex = /<translate(\s*.*)>(.*)<\/translate>/mg;
  23. let data = {}
  24. // replace all <translate param="value">Something</translate> into <span param="value">{this.props.p.t('Something')}</span>
  25. const result = source.replace(regex, function(match, p1, p2) {
  26. const md5 = crypto.createHash('md5').update(p2).digest("hex");
  27. data[md5] = p2;
  28. if(p1.trim() == 'span') {
  29. return "<span"+p1+">{this.props.p.t('"+md5+"')}</span>";
  30. } else if (p1.trim() == 'nojsx') {
  31. return "this.props.p.t('"+md5+"')";
  32. } else {
  33. return "{this.props.p.t('"+md5+"')}";
  34. }
  35. });
  36. const path = params.path+"/_"+chunk+".json";
  37. if (Object.keys(data).length !== 0) {
  38. fs.writeFile(path, JSON.stringify(data), function(err) {
  39. if(err) {
  40. return console.log(err);
  41. }
  42. });
  43. }
  44. return result;
  45. };