summaryrefslogtreecommitdiff
path: root/app/helpers/webpack_helper.rb
blob: 9d071f2d59a0e0ebf6ad33c33f5872388c21fe53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
require 'webpack/rails/manifest'

module WebpackHelper
  def webpack_bundle_tag(bundle, force_same_domain: false)
    javascript_include_tag(*gitlab_webpack_asset_paths(bundle, force_same_domain: force_same_domain))
  end

  def webpack_controller_bundle_tags
    bundles = []
    segments = [*controller.controller_path.split('/'), controller.action_name].compact

    until segments.empty?
      begin
        asset_paths = gitlab_webpack_asset_paths("pages.#{segments.join('.')}", extension: 'js')
        bundles.unshift(*asset_paths)
      rescue Webpack::Rails::Manifest::EntryPointMissingError
        # no bundle exists for this path
      end

      segments.pop
    end

    javascript_include_tag(*bundles)
  end

  # override webpack-rails gem helper until changes can make it upstream
  def gitlab_webpack_asset_paths(source, extension: nil, force_same_domain: false)
    return "" unless source.present?

    paths = Webpack::Rails::Manifest.asset_paths(source)
    if extension
      paths.select! { |p| p.ends_with? ".#{extension}" }
    end

    unless force_same_domain
      force_host = webpack_public_host
      if force_host
        paths.map! { |p| "#{force_host}#{p}" }
      end
    end

    paths
  end

  def webpack_public_host
    if Rails.env.test? && Rails.configuration.webpack.dev_server.enabled
      host = Rails.configuration.webpack.dev_server.host
      port = Rails.configuration.webpack.dev_server.port
      protocol = Rails.configuration.webpack.dev_server.https ? 'https' : 'http'
      "#{protocol}://#{host}:#{port}"
    else
      ActionController::Base.asset_host.try(:chomp, '/')
    end
  end

  def webpack_public_path
    relative_path = Rails.application.config.relative_url_root
    webpack_path = Rails.application.config.webpack.public_path
    File.join(webpack_public_host.to_s, relative_path.to_s, webpack_path.to_s, '')
  end
end