Skip to content

Instantly share code, notes, and snippets.

@reiterate-app
Created November 11, 2023 02:09
Show Gist options
  • Save reiterate-app/fc8d766be5f200c80a5830409b31a45a to your computer and use it in GitHub Desktop.
Save reiterate-app/fc8d766be5f200c80a5830409b31a45a to your computer and use it in GitHub Desktop.
Tailwind CSS for Jekyll
# frozen_string_literal: true
require 'pathname'
require 'Open3'
module Jekyll
class TailwindPlugin < Generator
priority :normal
def generate(site)
setup(site)
generate_css
static_file = AlwaysWriteFile.new(site, site.source, "/assets/css", "tailwind.css")
# Notify Jekyll that this file needs to be copied to the final site files
site.static_files << static_file
end
def setup(site)
config = site.config
@tailwind_script = config.dig('tailwind', 'script')
@tailwind_config = Pathname.new(config['source'] + '/tailwind.config.js')
@tailwind_output = Pathname.new(config['source'] + '/assets/css/tailwind.css')
tailwind_error "Please specify tailwind:script: in your config file" if @tailwind_script.nil?
tailwind_error "Tailwindcss processor #{@tailwind_script} not found" unless Pathname.new(@tailwind_script).exist?
tailwind_error "Tailwind config file #{@tailwind_config} missing" unless @tailwind_config.exist?
end
def generate_css
base_file_path = '/tmp/twbase.css'
File.write(base_file_path, TailwindBaseCSS)
stdout, stderr, status = Open3.capture3(@tailwind_script,
'--config', @tailwind_config.to_s,
'--input', base_file_path,
'--output', @tailwind_output.to_s)
if status.exitstatus != 0
tailwind_error(stderr)
end
end
def tailwind_error(msg)
Jekyll.logger.error "Tailwind:", msg
exit 1
end
TailwindBaseCSS =
<<~ENDCSS
@tailwind base;
@tailwind components;
@tailwind utilities;
ENDCSS
end
class AlwaysWriteFile < StaticFile
def modified?
true
end
def write(dest)
Jekyll.logger.info "Tailwind:", "Generated #{path}"
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment