dev.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. const debug = require('debug')('crowi:crowi:dev');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const webpack = require('webpack');
  5. const helpers = require('./helpers');
  6. const swig = require('swig-templates');
  7. const onHeaders = require('on-headers')
  8. class CrowiDev {
  9. /**
  10. * Creates an instance of CrowiDev.
  11. * @param {Crowi} crowi
  12. *
  13. * @memberOf CrowiDev
  14. */
  15. constructor(crowi) {
  16. this.crowi = crowi;
  17. }
  18. init() {
  19. this.requireForLiveReload();
  20. this.initPromiseRejectionWarningHandler();
  21. this.initSwig();
  22. }
  23. initPromiseRejectionWarningHandler() {
  24. // https://qiita.com/syuilo/items/0800d7e44e93203c7285
  25. process.on('unhandledRejection', console.dir);
  26. }
  27. initSwig() {
  28. swig.setDefaults({ cache: false });
  29. }
  30. /**
  31. * require files for live reloading
  32. */
  33. requireForLiveReload() {
  34. // environment file
  35. require(path.join(this.crowi.rootDir, 'config', 'env.dev.js'));
  36. // load all json files for live reloading
  37. fs.readdirSync(this.crowi.localeDir).map((dirname) => {
  38. require(path.join(this.crowi.localeDir, dirname, 'translation.json'));
  39. });
  40. }
  41. /**
  42. *
  43. *
  44. * @param {any} server http server
  45. * @param {any} app express
  46. *
  47. * @memberOf CrowiDev
  48. */
  49. setup(server, app) {
  50. this.setupHeaderDebugger(app);
  51. this.setupBrowserSync(app);
  52. }
  53. setupHeaderDebugger(app) {
  54. debug('setupHeaderDebugger');
  55. app.use((req, res, next) => {
  56. onHeaders(res, () => {
  57. debug('HEADERS GOING TO BE WRITTEN');
  58. });
  59. next();
  60. });
  61. }
  62. setupBrowserSync(app) {
  63. debug('setupBrowserSync');
  64. const browserSync = require('browser-sync');
  65. const bs = browserSync.create().init({
  66. logSnippet: false,
  67. notify: false,
  68. files: [
  69. `${this.crowi.viewsDir}/**/*.html`,
  70. `${this.crowi.publicDir}/**/*.js`,
  71. `${this.crowi.publicDir}/**/*.css`,
  72. ]
  73. });
  74. app.use(require('connect-browser-sync')(bs));
  75. }
  76. loadPlugins(app) {
  77. if (process.env.PLUGIN_NAMES_TOBE_LOADED !== undefined
  78. && process.env.PLUGIN_NAMES_TOBE_LOADED.length > 0) {
  79. const pluginNames = process.env.PLUGIN_NAMES_TOBE_LOADED.split(',');
  80. debug('loading Plugins for development', pluginNames);
  81. // merge and remove duplicates
  82. if (pluginNames.length > 0) {
  83. var PluginService = require('../plugins/plugin.service');
  84. var pluginService = new PluginService(this.crowi, app);
  85. pluginService.loadPlugins(pluginNames);
  86. }
  87. }
  88. }
  89. }
  90. module.exports = CrowiDev