start.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * React Static Boilerplate
  3. * https://github.com/koistya/react-static-boilerplate
  4. *
  5. * Copyright © 2015-2016 Konstantin Tarkus (@koistya)
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE.txt file in the root directory of this source tree.
  9. */
  10. const path = require('path')
  11. const browserSync = require('browser-sync')
  12. const webpack = require('webpack')
  13. const webpackDevMiddleware = require('webpack-dev-middleware')
  14. const webpackHotMiddleware = require('webpack-hot-middleware')
  15. const task = require('./task')
  16. const webpackConfig = require('../webpack.config')
  17. task('start', () => new Promise(resolve => {
  18. // Hot Module Replacement (HMR) + React Hot Reload
  19. if (webpackConfig.debug) {
  20. webpackConfig.entry.vendor
  21. .unshift('react-hot-loader/patch', 'webpack-hot-middleware/client')
  22. webpackConfig.module.loaders
  23. .find(x => x.loader === 'babel-loader').query.plugins
  24. .unshift('react-hot-loader/babel')
  25. webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
  26. webpackConfig.plugins.push(new webpack.NoErrorsPlugin())
  27. }
  28. const bundler = webpack(webpackConfig)
  29. browserSync({
  30. port: Number(process.env.PORT || 3000),
  31. ui: {
  32. port: Number(process.env.PORT || 3000) + 1,
  33. },
  34. server: {
  35. baseDir: './src',
  36. middleware: [
  37. webpackDevMiddleware(bundler, {
  38. // IMPORTANT: dev middleware can't access webpackConfig, so we should
  39. // provide publicPath by ourselves
  40. publicPath: webpackConfig.output.publicPath,
  41. // pretty colored output
  42. stats: webpackConfig.stats,
  43. // for other settings see
  44. // http://webpack.github.io/docs/webpack-dev-middleware.html
  45. }),
  46. // bundler should be the same as above
  47. webpackHotMiddleware(bundler),
  48. // Serve index.html for all unknown requests
  49. (req, res, next) => {
  50. if (req.headers.accept.startsWith('text/html')) {
  51. const filename = path.join(bundler.outputPath, 'index.html')
  52. bundler.outputFileSystem.readFile(filename, (err, result) => {
  53. if (err) {
  54. next(err)
  55. return
  56. }
  57. res.setHeader('Content-Type', 'text/html')
  58. res.end(result)
  59. })
  60. }
  61. next()
  62. },
  63. ],
  64. },
  65. // no need to watch '*.js' here, webpack will take care of it for us,
  66. // including full page reloads if HMR won't work
  67. files: [
  68. 'build/**/*.css',
  69. 'build/**/*.html',
  70. ],
  71. })
  72. resolve()
  73. }))