Module: NpmExt::Mkmf

Defined in:
lib/npm_ext/mkmf.rb

Defined Under Namespace

Classes: PackageEntry, RollupConfigPlugin

Constant Summary collapse

ROLLUP_PLUGINS =
i[
  @rollup/plugin-commonjs
  @rollup/plugin-node-resolve
  @rollup/plugin-json
  @rollup/plugin-terser
].freeze
ROLLUP_PACKAGES =
(ROLLUP_PLUGINS + i[rollup]).freeze

Instance Method Summary collapse

Instance Method Details

#create_npm_makefile(dir) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/npm_ext/mkmf.rb', line 67

def create_npm_makefile(dir)
  configs = create_rollup_config(dir)
  File.write("Makefile", "    sitearchdir ?= /tmp/\n    .PHONY: install\n    install:\n    \\tcp \#{dir}/package*.json ./ || :\n    \\tnpm ci\n    \\tnpm i \#{ROLLUP_PACKAGES.join(\" \")}\n    \#{configs.map do |_, x|\n      \"\\techo '\#{x[:rollup_config]}' > rollup.config.cjs && npx rollup --config && rm -rf rollup.config.cjs\"\n    end.join(\"\\n\")}\n    \\trm -rf npm_ext.so\n    \\tnode -e 'const fs = require(\"fs\"); fs.writeFileSync(\"npm_ext.so\", JSON.stringify(Object.fromEntries(\#{configs.transform_values { |x| x[:output_js] }.to_a.to_json}.map(([k, v]) => [k, fs.readFileSync(v, \"utf8\")]))))'\n    \\tcp npm_ext.so $(sitearchdir)$(target_prefix)\n    .PHONY: clean\n    clean:\n    \\trm -rf node_modules\n    \\trm -rf rollup.config.*.js\n    \\trm -rf *npm_ext.js\n    \\trm -rf npm_ext.so\n  MAKE\nend\n")

#create_rollup_config(dir) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/npm_ext/mkmf.rb', line 42

def create_rollup_config(dir)
  parse_package_json(dir).to_h do |package|
    hash = Digest::MD5.hexdigest(package.name.to_s)
    output_js = "#{hash}.npm_ext.js"
    config = "module.exports = #{JSON.generate(
      {
        # TODO: if no file provided get the input file from package.json
        input: "node_modules/#{package.name}/#{package.file_to_bundle}",
        output: {
          file: output_js,
          name: package.name,
          format: "iife",
        },
        plugins: ROLLUP_PLUGINS.map do |x|
          RollupConfigPlugin.new x
        end,
      },
    )}"
    [package.name, {
      rollup_config: config,
      output_js: output_js,
    }]
  end
end

#parse_package_json(dir) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/npm_ext/mkmf.rb', line 32

def parse_package_json(dir)
  packages = JSON.parse(File.read("#{dir}/package.json"), symbolize_names: true)
  packages[:dependencies].map do |x, _|
    PackageEntry.new(
      name: x,
      file_to_bundle: packages[:fileToBundle][x],
    )
  end
end