routes-loader.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * React Static Boilerplate
  3. * https://github.com/koistya/react-static-boilerplate
  4. * Copyright (c) Konstantin Tarkus (@koistya) | MIT license
  5. */
  6. import glob from 'glob';
  7. import { join } from 'path';
  8. export default function (source) {
  9. this.cacheable();
  10. const target = this.target;
  11. const callback = this.async();
  12. if (target === 'node') {
  13. source = source.replace('import \'babel/polyfill\';', '');
  14. }
  15. glob('**/*.{js,jsx}', { cwd: join(__dirname, '../../src') }, function(err, files) {
  16. if (err) {
  17. return callback(err);
  18. }
  19. const lines = files.filter(file => !file.startsWith('js/')).map(file => {
  20. var path = '/' + file;
  21. if (path === '/index.js' || path === '/index.jsx') {
  22. path = '/';
  23. } else if (path.endsWith('/index.js')) {
  24. path = path.substr(0, path.length - 9);
  25. } else if (path.endsWith('/index.jsx')) {
  26. path = path.substr(0, path.length - 10);
  27. } else if (path.endsWith('.js')) {
  28. path = path.substr(0, path.length - 3);
  29. } else if (path.endsWith('.jsx')) {
  30. path = path.substr(0, path.length - 4);
  31. }
  32. if (target === 'node' || path === '/404' || path === '/500') {
  33. return ` '${path}': () => require('../${file}'),`;
  34. } else {
  35. return ` '${path}': () => new Promise(resolve => require(['../${file}'], resolve)),`;
  36. }
  37. });
  38. if (lines.length) {
  39. return callback(null, source.replace(' routes = {', ' routes = {\n' + lines.join('')));
  40. } else {
  41. return callback(new Error('Cannot find any routes.'));
  42. }
  43. });
  44. };