Module: PetiteVite::ViewHelper

Defined in:
lib/petite_vite_rails/view_helper.rb

Instance Method Summary collapse

Instance Method Details

#vite_tagsObject



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
# File 'lib/petite_vite_rails/view_helper.rb', line 3

def vite_tags
  if Rails.env.development?
    port = PetiteVite.config.vite_dev_server_port
    frontend_output = PetiteVite.config.frontend_output.sub(%r{^/+}, "")
    <<~SCRIPTS.html_safe
      <script type="module" src="http://localhost:#{port}/@vite/client"></script>
      <script type="module" src="http://localhost:#{port}/#{frontend_output}"></script>
    SCRIPTS
  else
    # https://vite.dev/guide/backend-integration.html
    #
    # <!-- 0. if production -->
    #
    # <!-- 1. for cssFile of manifest[name].css -->
    # <link rel="stylesheet" href="/{{ cssFile }}" />
    #
    # <!-- 2. for chunk of importedChunks(manifest, name) -->
    # <!-- 3. for cssFile of chunk.css -->
    # <link rel="stylesheet" href="/{{ cssFile }}" />
    #
    # <!-- 4 -->
    # <script type="module" src="/{{ manifest[name].file }}"></script>
    #
    # <!-- 5. for chunk of importedChunks(manifest, name) -->
    # <link rel="modulepreload" href="/{{ chunk.file }}" />

    out = []
    PetiteVite.config.manifest.contents.each do |_name, chunk|
      next if !chunk["isEntry"]
      # 1
      chunk["css"]&.each do |css|
        out.push(%(<link rel="stylesheet" href="/#{css}" />))
      end
      # 2
      chunk["dynamicImports"]&.each do |imported_name|
        # 3
        imported_chunk = PetiteVite.config.manifest.contents[imported_name]
        imported_chunk["css"]&.each do |css|
          out.push(%(<link rel="stylesheet" href="/#{css}" />))
        end
      end
      # 4
      out.push(%(<script type="module" src="/#{chunk.fetch("file")}"></script>))
      # 5
      chunk["dynamicImports"]&.each do |imported_name|
        imported_chunk = PetiteVite.config.manifest.contents[imported_name]
        out.push(%(<link rel="modulepreload" href="/#{imported_chunk.fetch("file")}" />))
      end
    end

    out.join("\n").html_safe
  end
end