lib/jekyll/esm.rb in jekyll-esm-0.0.3 vs lib/jekyll/esm.rb in jekyll-esm-0.1.0
- old
+ new
@@ -7,10 +7,13 @@
require 'nokogiri'
require 'json'
module Jekyll
module Esm
+ @@existing_esm_packages = []
+ @@new_esm_packages = []
+
class Error < StandardError; end
def self.process(page)
doc = Nokogiri::HTML(page.output)
@@ -18,11 +21,17 @@
import_maps.each do |value|
importmap = JSON.parse(value.children[0].content)
imports = importmap["imports"]
imports.keys.each do |import|
+ pkg_path = File.join(page.site.source, 'node_modules', import)
+ # don't repeatedly attempt to install a package
+ return if Dir.exists?(pkg_path) && @@new_esm_packages.include?(import)
+
+ @@new_esm_packages << import
+
stdout, stderr, status = Open3.capture3(
"yarn add #{import}",
chdir: File.expand_path(page.site.source)
)
@@ -32,18 +41,33 @@
raise Error, stderr if stderr.size > 0
raise Error, stdout if !runtime_error.nil?
end
end
end
-
end
def self.apply(site)
- FileUtils.cp_r(File.join(site.source, 'node_modules'), File.join(site.dest, 'node_modules'))
- end
+ existing_packages = Dir.children(File.join(site.source, 'node_modules')).reject { |dir| dir =~ /^\..*$/ }
+ for_removal = existing_packages - @@new_esm_packages.uniq
- private
+ # Remove any packages that are no longer referenced in an esm declaration
+ if for_removal.any?
+ stdout, stderr, status = Open3.capture3(
+ "yarn remove #{for_removal.join(' ')}",
+ chdir: File.expand_path(site.source)
+ )
+ if site.config.dig('esm', 'strict')
+ runtime_error = stdout =~ /ERROR in|SyntaxError/
+
+ raise Error, stderr if stderr.size > 0
+ raise Error, stdout if !runtime_error.nil?
+ end
+ end
+
+ FileUtils.cp_r(File.join(site.source, 'node_modules'), File.join(site.dest, 'node_modules'))
+ @@new_esm_packages = []
+ end
end
end
Jekyll::Hooks.register :pages, :post_render do |page|