You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.9 KiB

  1. #!/usr/bin/env ruby
  2. $stdout.sync = true
  3. require "shellwords"
  4. require "yaml"
  5. require "socket"
  6. ENV["RAILS_ENV"] ||= "development"
  7. RAILS_ENV = ENV["RAILS_ENV"]
  8. ENV["NODE_ENV"] ||= RAILS_ENV
  9. NODE_ENV = ENV["NODE_ENV"]
  10. APP_PATH = File.expand_path("../", __dir__)
  11. CONFIG_FILE = File.join(APP_PATH, "config/webpacker.yml")
  12. NODE_MODULES_PATH = File.join(APP_PATH, "node_modules")
  13. WEBPACK_CONFIG = File.join(APP_PATH, "config/webpack/#{NODE_ENV}.js")
  14. DEFAULT_LISTEN_HOST_ADDR = NODE_ENV == 'development' ? 'localhost' : '0.0.0.0'
  15. def args(key)
  16. index = ARGV.index(key)
  17. index ? ARGV[index + 1] : nil
  18. end
  19. begin
  20. dev_server = YAML.load_file(CONFIG_FILE)[RAILS_ENV]["dev_server"]
  21. HOSTNAME = args('--host') || dev_server["host"]
  22. PORT = args('--port') || dev_server["port"]
  23. HTTPS = ARGV.include?('--https') || dev_server["https"]
  24. DEV_SERVER_ADDR = "http#{"s" if HTTPS}://#{HOSTNAME}:#{PORT}"
  25. LISTEN_HOST_ADDR = args('--listen-host') || DEFAULT_LISTEN_HOST_ADDR
  26. rescue Errno::ENOENT, NoMethodError
  27. $stdout.puts "Webpack dev_server configuration not found in #{CONFIG_FILE}."
  28. $stdout.puts "Please run bundle exec rails webpacker:install to install webpacker"
  29. exit!
  30. end
  31. begin
  32. server = TCPServer.new(LISTEN_HOST_ADDR, PORT)
  33. server.close
  34. rescue Errno::EADDRINUSE
  35. $stdout.puts "Another program is running on port #{PORT}. Set a new port in #{CONFIG_FILE} for dev_server"
  36. exit!
  37. end
  38. # Delete supplied host, port and listen-host CLI arguments
  39. ["--host", "--port", "--listen-host"].each do |arg|
  40. ARGV.delete(args(arg))
  41. ARGV.delete(arg)
  42. end
  43. env = { "NODE_PATH" => NODE_MODULES_PATH.shellescape }
  44. cmd = [
  45. "#{NODE_MODULES_PATH}/.bin/webpack-dev-server", "--progress", "--color",
  46. "--config", WEBPACK_CONFIG,
  47. "--host", LISTEN_HOST_ADDR,
  48. "--public", "#{HOSTNAME}:#{PORT}",
  49. "--port", PORT.to_s
  50. ] + ARGV
  51. Dir.chdir(APP_PATH) do
  52. exec env, *cmd
  53. end