routes-loader.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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\';', ''); // eslint-disable-line no-param-reassign
  14. }
  15. glob('**/*.{js,jsx}', { cwd: join(__dirname, '../../pages') }, (err, files) => {
  16. if (err) {
  17. return callback(err);
  18. }
  19. const lines = files.map(file => {
  20. let 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('./pages/${file}'),`;
  34. }
  35. return ` '${path}': () => new Promise(resolve => require(['./pages/${file}'], resolve)),`;
  36. });
  37. if (lines.length) {
  38. return callback(null, source.replace(' routes = {', ' routes = {\n' + lines.join('')));
  39. }
  40. return callback(new Error('Cannot find any routes.'));
  41. });
  42. }