importmap-rails 0.4.3 → 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 06f09e5cb89d870d3ef6b604e8161926a454a81e86aef033b8a3cd65274543af
4
- data.tar.gz: 7027b536650f7ad0d320d70d30e09c525853b0949b857ff8da8aac2ebbe87ec3
3
+ metadata.gz: 97b5ca5be348b06c3b3b04b5aaccc99fa5bc55a8a65c664d25e37cf6f8be2586
4
+ data.tar.gz: 3c377792bec10f97d819640e801dc9a36112ef009da0902eba36a2d873d67623
5
5
  SHA512:
6
- metadata.gz: f31d17177dce653b7f2ff9eef08245b52c5ccf12ab5f7536796116b771f702486ee0081e4c345d215cd69cacdaefddd6694307d684be972f61e6afa13f9fe84b
7
- data.tar.gz: a38b6fd51717b34ef57a751f2adc882827c05a585a8a3fe87ec695bbe523f5e7657d9bfbb98da9ddcacff7ff83b3230ecf8e3167069471b3c9801fe65855679f
6
+ metadata.gz: 66c0ee6695329e2cba7e6bdf545d4415fa3bc92218fff791ec21977f53fe8294c536cf5fefba0d00c7ceb5859529e32c2cadbbad0097c21bd82efba84402a0f7
7
+ data.tar.gz: 95be4c078375c1e11f7061dedc195c9bbec3f57e870104ef429e64586100f8872ba4ab94398b4b7e6003e07a77514d7a74682428b8e1b85d889bf028c43a8683
data/README.md CHANGED
@@ -1,49 +1,48 @@
1
1
  # Importmap for Rails
2
2
 
3
- [Import maps](https://github.com/WICG/import-maps) let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. So you can build modern JavaScript applications using JavaScript libraries made for ESM without the need for transpiling or bundling. Without the need for such preprocessing, you can build advanced Rails applications without Webpack, Yarn, NPM, or any other part of the JavaScript toolchain. All you need is the asset pipeline that's already included in Rails.
3
+ [Import maps](https://github.com/WICG/import-maps) let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. So you can [build modern JavaScript applications using JavaScript libraries made for ESM without the need for transpiling or bundling](https://world.hey.com/dhh/modern-web-apps-without-javascript-bundling-or-transpiling-a20f2755).This frees you from needing Webpack, Yarn, npm, or any other part of the JavaScript toolchain. All you need is the asset pipeline that's already included in Rails.
4
4
 
5
- With this approach you'll ship many small JavaScript files instead of one big JavaScript file. Thanks to HTTP2 that no longer carries a material performance penalty during the initial transport, and in fact offers substantial benefits over the long run due to better caching dynamics. Whereas before, any change to any JavaScript file included in your big bundle would invalidate the cache for the the whole bundle, now only the cache for that single file is invalidated.
5
+ With this approach you'll ship many small JavaScript files instead of one big JavaScript file. Thanks to HTTP2 that no longer carries a material performance penalty during the initial transport, and in fact offers substantial benefits over the long run due to better caching dynamics. Whereas before any change to any JavaScript file included in your big bundle would invalidate the cache for the the whole bundle, now only the cache for that single file is invalidated.
6
6
 
7
7
  There's [native support for import maps in Chrome/Edge 89+](https://caniuse.com/?search=importmap), and [a shim available](https://github.com/guybedford/es-module-shims) for any browser with basic ESM support. So your app will be able to work with all the evergreen browsers.
8
8
 
9
9
 
10
10
  ## Installation
11
11
 
12
- 1. Add `importmap-rails` to your Gemfile with `gem 'importmap-rails'` (make sure it's included before any gems using it!)
12
+ Importmap for Rails is automatically included in Rails 7+ for new applications, but you can also install it manually in existing applications:
13
+
14
+ 1. Add `importmap-rails` to your Gemfile with `gem 'importmap-rails'`
13
15
  2. Run `./bin/bundle install`
14
16
  3. Run `./bin/rails importmap:install`
15
17
 
16
- By default, all the files in `app/assets/javascripts` and the three major Rails JavaScript libraries are already mapped. You can add more mappings in `config/importmap.rb`.
17
-
18
18
  Note: In order to use JavaScript from Rails frameworks like Action Cable, Action Text, and Active Storage, you must be running Rails 7.0+. This was the first version that shipped with ESM compatible builds of these libraries.
19
19
 
20
20
 
21
21
  ## Usage
22
22
 
23
- The import map is configured programmatically through the `Rails.application.config.importmap` assignment, which by default is setup in `config/importmap.rb` after running the installer. This file is automatically reloaded in development upon changes, but note that you must restart the server if you remove pins and need them gone from the rendered importmap or list of preloads.
23
+ The import map is setup through `Rails.application.config.importmap` via the configuration in `config/importmap.rb`. This file is automatically reloaded in development upon changes, but note that you must restart the server if you remove pins and need them gone from the rendered importmap or list of preloads.
24
24
 
25
- This programmatically configured import map is inlined in the `<head>` of your application layout using `<%= javascript_importmap_tags %>`, which will setup the JSON configuration inside a `<script type="importmap">` tag. After that, the [es-module-shim](https://github.com/guybedford/es-module-shims) is loaded, and then finally the application entrypoint is imported via `<script type="module">import "application"</script>`. That logical entrypoint, `application`, is mapped in the importmap script tag to the file `app/javascript/application.js`, which is copied and digested by the asset pipeline.
25
+ This import map is inlined in the `<head>` of your application layout using `<%= javascript_importmap_tags %>`, which will setup the JSON configuration inside a `<script type="importmap">` tag. After that, the [es-module-shim](https://github.com/guybedford/es-module-shims) is loaded, and then finally the application entrypoint is imported via `<script type="module">import "application"</script>`. That logical entrypoint, `application`, is mapped in the importmap script tag to the file `app/javascript/application.js`.
26
26
 
27
27
  It's in `app/javascript/application.js` you setup your application by importing any of the modules that have been defined in the import map. You can use the full ESM functionality of importing any particular export of the modules or everything.
28
28
 
29
- It makes sense to use logical names that match the package names used by NPM, such that if you later want to start transpiling or bundling your code, you'll not have to change any module imports.
29
+ It makes sense to use logical names that match the package names used by npm, such that if you later want to start transpiling or bundling your code, you won't have to change any module imports.
30
30
 
31
31
 
32
32
  ## Using node modules via JavaScript CDNs
33
33
 
34
34
  Importmap for Rails is designed to be used with JavaScript CDNs for your node package dependencies. The CDNs provide pre-compiled distribution versions ready to use, and offer a fast, efficient way of serving them.
35
35
 
36
- You can use the `./bin/importmap` command that's added as part of the install to pin additional packages to your import map. This command uses an API from [JSPM.org](https://jspm.org) to resolve your package dependencies most efficiently, and then add the pins to your `config/importmap.rb` file. It can resolve these dependencies from JSPM itself, but also from other CDNs, like [unpkg.com](https://unpkg.com), [jsdelivr.com](https://www.jsdelivr.com), [skypack.dev](https://www.skypack.dev), etc.
36
+ You can use the `./bin/importmap` command that's added as part of the install to pin, unpin, or update node packages in your import map. This command uses an API from [JSPM.org](https://jspm.org) to resolve your package dependencies efficiently, and then add the pins to your `config/importmap.rb` file. It can resolve these dependencies from JSPM itself, but also from other CDNs, like [unpkg.com](https://unpkg.com) and [jsdelivr.com](https://www.jsdelivr.com).
37
37
 
38
38
  It works like so:
39
39
 
40
40
  ```bash
41
- ./bin/importmap pin react react-dom
42
-
43
- Pinned 'react' to https://ga.jspm.io/npm:react@17.0.2/index.js
44
- Pinned 'react-dom' to https://ga.jspm.io/npm:react-dom@17.0.2/index.js
45
- Pinned 'object-assign' to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
46
- Pinned 'scheduler' to https://ga.jspm.io/npm:scheduler@0.20.2/index.js
41
+ /bin/importmap pin react react-dom
42
+ Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/index.js
43
+ Pinning "react-dom" to https://ga.jspm.io/npm:react-dom@17.0.2/index.js
44
+ Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
45
+ Pinning "scheduler" to https://ga.jspm.io/npm:scheduler@0.20.2/index.js
47
46
 
48
47
  ./bin/importmap json
49
48
 
@@ -67,12 +66,65 @@ import React from "react"
67
66
  import ReactDOM from "react-dom"
68
67
  ```
69
68
 
70
- Run `./bin/importmap` to see more options.
69
+ You can also designate a specific version to pin:
70
+
71
+ ```bash
72
+ ./bin/importmap pin react@17.0.1
73
+ Pinning "react" to https://ga.jspm.io/npm:react@17.0.1/index.js
74
+ Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
75
+ ```
76
+
77
+ Or even remove pins:
78
+
79
+ ```bash
80
+ ./bin/importmap unpin react
81
+ Unpinning "react"
82
+ Unpinning "object-assign"
83
+ ```
84
+
85
+ If you pin a package that has already been pinned, it'll be updated inline, along with its dependencies.
86
+
87
+ You can control the environment of the package for packages with separate "production" (the default) and "development" builds:
88
+
89
+ ```bash
90
+ ./bin/importmap pin react --env development
91
+ Pinning "react" to https://ga.jspm.io/npm:react@17.0.2/dev.index.js
92
+ Pinning "object-assign" to https://ga.jspm.io/npm:object-assign@4.1.1/index.js
93
+ ```
94
+
95
+ You can also pick an alternative, supported CDN provider when pinning, like `unpkg` or `jsdelivr` (`jspm` is the default):
96
+
97
+ ```bash
98
+ ./bin/importmap pin react --from jsdelivr
99
+ Pinning "react" to https://cdn.jsdelivr.net/npm/react@17.0.2/index.js
100
+ ```
101
+
102
+ Remember, though, that if you switch a pin from one provider to another, you may have to clean up dependencies added by the first provider that isn't used by the second provider.
103
+
104
+ Run `./bin/importmap` to see all options.
105
+
106
+ Note that this command is merely a convenience wrapper to resolving logical package names to CDN URLs. You can also just lookup the CDN URLs yourself, and then pin those. For example, if you wanted to use Skypack for React, you could just add the following to `config/importmap.rb`:
107
+
108
+ ```ruby
109
+ pin "react", to: "https://cdn.skypack.dev/react"
110
+ ```
111
+
112
+
113
+ ## What if I don't like to use a JavaScript CDN?
114
+
115
+ You always have the option to simply download the compiled JavaScript packages from the CDNs, and saving them locally in your application. You can put such files in app/javascript/vendor, and then reference them with local pins, like:
116
+
117
+ ```ruby
118
+ # config/importmap.rb
119
+ pin "react", to: "vendor/react@17.0.2.js"
120
+ ```
121
+
122
+ But using a JavaScript CDN is fast, secure, and easier to deal with. Start there.
71
123
 
72
124
 
73
125
  ## Preloading pinned modules
74
126
 
75
- To mitigate the waterfall effect where the browser has to load one file after another before it can get to the deepest nested import, we use [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload). Pinned modules are preloaded by default, but you can turn this off with `preload: false`.
127
+ To avoid the waterfall effect where the browser has to load one file after another before it can get to the deepest nested import, we use [modulepreload links](https://developers.google.com/web/updates/2017/12/modulepreload). Pinned modules are preloaded by default, but you can turn this off with `preload: false`.
76
128
 
77
129
  Example:
78
130
 
@@ -29,7 +29,7 @@ module Importmap::ImportmapTagsHelper
29
29
  # (defaults to Rails.application.config.importmap), such that they'll be fetched
30
30
  # in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
31
31
  def javascript_importmap_module_preload_tags(importmap = Rails.application.config.importmap)
32
- javascript_module_preload_tag *importmap.preloaded_module_paths(resolver: self)
32
+ javascript_module_preload_tag(*importmap.preloaded_module_paths(resolver: self))
33
33
  end
34
34
 
35
35
  # Link tag(s) for preloading the JavaScript module residing in `*paths`. Will return one link tag per path element.
@@ -1,14 +1,40 @@
1
1
  require "thor"
2
- require "importmap/pinner"
2
+ require "importmap/packager"
3
3
 
4
4
  class Importmap::Commands < Thor
5
+ include Thor::Actions
6
+
5
7
  desc "pin [*PACKAGES]", "Pin new packages"
6
8
  option :env, type: :string, aliases: :e, default: "production"
7
9
  option :from, type: :string, aliases: :f, default: "jspm"
8
10
  def pin(*packages)
9
- if imports = Importmap::Pinner.new.pin(*packages, env: options[:env], from: options[:from])
11
+ if imports = packager.import(*packages, env: options[:env], from: options[:from])
10
12
  imports.each do |package, url|
11
- puts "Pinned '#{package}' to #{url}"
13
+ puts %(Pinning "#{package}" to #{url})
14
+
15
+ pin = packager.pin_for(package, url)
16
+
17
+ if packager.packaged?(package)
18
+ gsub_file("config/importmap.rb", /^pin "#{package}".*$/, pin, verbose: false)
19
+ else
20
+ append_to_file("config/importmap.rb", "#{pin}\n", verbose: false)
21
+ end
22
+ end
23
+ else
24
+ puts "Couldn't find any packages in #{packages.inspect} on #{options[:provider]}"
25
+ end
26
+ end
27
+
28
+ desc "unpin [*PACKAGES]", "Unpin existing packages"
29
+ option :env, type: :string, aliases: :e, default: "production"
30
+ option :from, type: :string, aliases: :f, default: "jspm"
31
+ def unpin(*packages)
32
+ if imports = packager.import(*packages, env: options[:env], from: options[:from])
33
+ imports.each do |package, url|
34
+ if packager.packaged?(package)
35
+ puts %(Unpinning "#{package}")
36
+ remove_line_from_file "config/importmap.rb", /pin "#{package}"/
37
+ end
12
38
  end
13
39
  else
14
40
  puts "Couldn't find any packages in #{packages.inspect} on #{options[:provider]}"
@@ -19,6 +45,22 @@ class Importmap::Commands < Thor
19
45
  def json
20
46
  puts Rails.application.config.importmap.to_json(resolver: ActionController::Base.helpers)
21
47
  end
48
+
49
+ private
50
+ def packager
51
+ @packager ||= Importmap::Packager.new
52
+ end
53
+
54
+ def remove_line_from_file(path, pattern)
55
+ path = File.expand_path(path, destination_root)
56
+
57
+ all_lines = File.readlines(path)
58
+ with_lines_removed = all_lines.select { |line| line !~ pattern }
59
+
60
+ File.open(path, "w") do |file|
61
+ with_lines_removed.each { |line| file.write(line) }
62
+ end
63
+ end
22
64
  end
23
65
 
24
66
  Importmap::Commands.start(ARGV)
@@ -0,0 +1,39 @@
1
+ require "httparty"
2
+ require "minitest/mock"
3
+
4
+ class Importmap::Packager
5
+ include HTTParty
6
+ base_uri "https://api.jspm.io"
7
+
8
+ def initialize(importmap_path = "config/importmap.rb")
9
+ @importmap_path = importmap_path
10
+ end
11
+
12
+ def import(*packages, env: "production", from: "jspm")
13
+ response = self.class.post("/generate", body: {
14
+ "install" => Array(packages),
15
+ "flattenScope" => true,
16
+ "env" => [ "browser", "module", env ],
17
+ "provider" => from.to_s
18
+ }.to_json)
19
+
20
+ case response.code
21
+ when 200 then response.dig("map", "imports")
22
+ when 404 then nil
23
+ else response.send(:throw_exception)
24
+ end
25
+ end
26
+
27
+ def pin_for(package, url)
28
+ %(pin "#{package}", to: "#{url}")
29
+ end
30
+
31
+ def packaged?(package)
32
+ importmap.match(/^pin "#{package}".*$/)
33
+ end
34
+
35
+ private
36
+ def importmap
37
+ @importmap ||= File.read(@importmap_path)
38
+ end
39
+ end
@@ -1,3 +1,3 @@
1
1
  module Importmap
2
- VERSION = "0.4.3"
2
+ VERSION = "0.5.0"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: importmap-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.3
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Heinemeier Hansson
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2021-08-31 00:00:00.000000000 Z
11
+ date: 2021-09-01 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -54,7 +54,7 @@ files:
54
54
  - lib/importmap/commands.rb
55
55
  - lib/importmap/engine.rb
56
56
  - lib/importmap/map.rb
57
- - lib/importmap/pinner.rb
57
+ - lib/importmap/packager.rb
58
58
  - lib/importmap/reloader.rb
59
59
  - lib/importmap/version.rb
60
60
  - lib/install/bin/importmap
@@ -1,32 +0,0 @@
1
- require "httparty"
2
-
3
- class Importmap::Pinner
4
- include HTTParty
5
- base_uri "https://api.jspm.io"
6
-
7
- def pin(*packages, env: "production", from: "jspm")
8
- fetch_imports(*packages, env: env, provider: from)&.tap do |imports|
9
- imports.each do |package, url|
10
- append_to_importmap package, url
11
- end
12
- end
13
- end
14
-
15
- private
16
- def append_to_importmap(package, url)
17
- Rails.root.join("config/importmap.rb").open("a") do |config|
18
- config.puts %(pin "#{package}", to: "#{url}")
19
- end
20
- end
21
-
22
- def fetch_imports(*packages, env:, provider:)
23
- response = self.class.post("/generate", body: {
24
- "install" => Array(packages),
25
- "flattenScope" => true,
26
- "env" => [ "browser", "module", env ],
27
- "provider" => provider.to_s
28
- }.to_json)
29
-
30
- response.dig("map", "imports")
31
- end
32
- end