|
| 1 | +require "shellwords" |
| 2 | +require "yaml" |
| 3 | +require "socket" |
| 4 | +require "webpacker/runner" |
| 5 | + |
| 6 | +module Webpacker |
| 7 | + class DevServerRunner < Webpacker::Runner |
| 8 | + def run |
| 9 | + load_config |
| 10 | + detect_port! |
| 11 | + execute_cmd |
| 12 | + end |
| 13 | + |
| 14 | + private |
| 15 | + |
| 16 | + def load_config |
| 17 | + @config_file = File.join(@app_path, "config/webpacker.yml") |
| 18 | + @default_listen_host_addr = ENV["NODE_ENV"] == "development" ? "localhost" : "0.0.0.0" |
| 19 | + |
| 20 | + dev_server = YAML.load_file(@config_file)[ENV["RAILS_ENV"]]["dev_server"] |
| 21 | + |
| 22 | + @hostname = args("--host") || dev_server["host"] |
| 23 | + @port = args("--port") || dev_server["port"] |
| 24 | + @https = @argv.include?("--https") || dev_server["https"] |
| 25 | + @dev_server_addr = "http#{"s" if @https}://#{@hostname}:#{@port}" |
| 26 | + @listen_host_addr = args("--listen-host") || @default_listen_host_addr |
| 27 | + |
| 28 | + rescue Errno::ENOENT, NoMethodError |
| 29 | + $stdout.puts "Webpack dev_server configuration not found in #{@config_file}." |
| 30 | + $stdout.puts "Please run bundle exec rails webpacker:install to install webpacker" |
| 31 | + exit! |
| 32 | + end |
| 33 | + |
| 34 | + def detect_port! |
| 35 | + server = TCPServer.new(@listen_host_addr, @port) |
| 36 | + server.close |
| 37 | + |
| 38 | + rescue Errno::EADDRINUSE |
| 39 | + $stdout.puts "Another program is running on port #{@port}. Set a new port in #{@config_file} for dev_server" |
| 40 | + exit! |
| 41 | + end |
| 42 | + |
| 43 | + def execute_cmd |
| 44 | + argv = @argv.dup |
| 45 | + |
| 46 | + # Delete supplied host, port and listen-host CLI arguments |
| 47 | + ["--host", "--port", "--listen-host"].each do |arg| |
| 48 | + argv.delete(args(arg)) |
| 49 | + argv.delete(arg) |
| 50 | + end |
| 51 | + |
| 52 | + env = { "NODE_PATH" => @node_modules_path.shellescape } |
| 53 | + |
| 54 | + cmd = [ |
| 55 | + "#{@node_modules_path}/.bin/webpack-dev-server", "--progress", "--color", |
| 56 | + "--config", @webpack_config, |
| 57 | + "--host", @listen_host_addr, |
| 58 | + "--public", "#{@hostname}:#{@port}", |
| 59 | + "--port", @port.to_s |
| 60 | + ] + argv |
| 61 | + |
| 62 | + Dir.chdir(@app_path) do |
| 63 | + exec env, *cmd |
| 64 | + end |
| 65 | + end |
| 66 | + |
| 67 | + def args(key) |
| 68 | + index = @argv.index(key) |
| 69 | + index ? @argv[index + 1] : nil |
| 70 | + end |
| 71 | + end |
| 72 | +end |
0 commit comments