Class: Brut::CLI::Apps::BuildAssets::Js

Inherits:
BaseCommand show all
Defined in:
lib/brut/cli/apps/build_assets.rb

Instance Attribute Summary

Attributes inherited from Commands::BaseCommand

#parent_command

Instance Method Summary collapse

Methods inherited from BaseCommand

#bootstrap?, #default_rack_env, #friendly_name

Methods inherited from Commands::BaseCommand

#accepts, #args_description, #argv, #bootstrap?, #commands, #default_rack_env, #delegate_to_command, #detailed_description, #env, #env_vars, #execute, #name, #options, #puts, #stdin, #system!, #theme

Instance Method Details

#descriptionObject



135
# File 'lib/brut/cli/apps/build_assets.rb', line 135

def description = "Builds and bundles JavaScript destined for the browser"

#optsObject



136
137
138
139
140
141
142
143
144
145
# File 'lib/brut/cli/apps/build_assets.rb', line 136

def opts = super + [
  [
    "--output-file=FILE",
    "Bundle to create that will be sent to the browser, relative to the JS public folder. Default is app.js",
  ],
  [
    "--source-file=FILE",
    "Entry point used to create the bundle, relative to the source JS folder. Default is index.js",
  ],
]

#runObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/brut/cli/apps/build_assets.rb', line 147

def run
  js_bundle           = Brut.container.js_bundle_output_dir / options.output_file(default: "app.js")
  js_bundle_source    = Brut.container.front_end_src_dir /  "js" / options.source_file(default: "index.js")
  esbuild_metafile    = Brut.container.tmp_dir / "build-js-meta.json"
   = Brut.container.

  name_with_hash_regexp = /app\/public\/(?<path>.+)\/(?<name>.+)\-(?<hash>.+)\.js/
  if options.clean?(default: options.env != "production")
    puts "Cleaning old JS files from #{friendly_name(Brut.container.js_bundle_output_dir)}"
    Dir[Brut.container.js_bundle_output_dir / "*.*"].each do |file|
      if File.file?(file)
        puts theme.weak.render("  Deleting #{theme.code.render(friendly_name(file))}")
        FileUtils.rm(file)
      end
    end
  end

  # NOTE: esbuild outputs its normal messages on stderr which is fucking stupid
  command = "npx esbuild --metafile=#{esbuild_metafile} --entry-names=[name]-[hash] --sourcemap --bundle #{js_bundle_source} --outfile=#{js_bundle} 2>&1"
  puts "Building JS bundle '#{theme.code.render(friendly_name(js_bundle))}'"
  system!(command)

  if !File.exist?(esbuild_metafile)
    error "'#{esbuild_metafile}' was not generated - cannot continue"
    return 1
  end

   = Brut::FrontEnd::AssetMetadata.new(asset_metadata_file:,logger: execution_context.logger)
  .merge!(extension: ".js", esbuild_metafile:)
  .save!
  0
end