importmap-rails 0.4.2 → 0.5.2

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: 90c8dfc1a293d3e6f5e1fbfdac6a7852a54d4fefe0179874adccccef986ffb70
4
- data.tar.gz: f54c20b0877bcf7e0a88cb15ab9a05dbeb81638c0a48a1a16687880e2e651332
3
+ metadata.gz: 19ceaae3202d5f82c6ef2b17bfc294b3330a792a809c575eb0f959bd0f57aba4
4
+ data.tar.gz: 136f545bb38d4076dd6314bb2d35cb706d64fe2903f552c0ce1bbbf977549794
5
5
  SHA512:
6
- metadata.gz: c56e463c75ffb6e1d39d6d7edd2ab1da88d13abd674fe4db7f6cf056a505253800e121ea8cf8880d6f7eca29831340cc6e3c55f79efb66b1da2faf034935f5fd
7
- data.tar.gz: 20e1e5e714d63e188ad265f7b01130803bb4c2881aa1b65cccf3adfdcb168f891b9deb7e0f3899a9248c5cf321e47311a1dfaa7f78a5f128f346b164833f1e02
6
+ metadata.gz: 332685ead888c7ea3c0de2187a6c34fbb0966e0806f31d6fa953483508623bdaec66add67f1a176fc74411530c76c2e1cfb465d1a95a5ce9b6a9163d57d24ecc
7
+ data.tar.gz: 1a8c37e746483245f90d8f3e763c321dca4bf363fdcd1a44802af48582637abafe05ac3af90fbd53e1cae1a612334a3ce9e15b06d4c11be9cea838448475732d
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
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
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
 
@@ -89,6 +141,32 @@ pin "md5", to: "https://cdn.jsdelivr.net/npm/md5@2.3.0/md5.js", preload: false
89
141
  ...
90
142
  ```
91
143
 
144
+ ## Composing import maps
145
+
146
+ By default, Rails loads import map definition from the application's `config/importmap.rb` to the `Importmap::Map` object available at `Rails.application.config.importmap`.
147
+
148
+ You can combine multiple import maps by drawing their definitions onto the `Rails.application.config.importmap`. For example, appending import maps defined in Rails engines:
149
+
150
+ ```ruby
151
+ # my_engine/lib/my_engine/engine.rb
152
+
153
+ module MyEngine
154
+ class Engine < ::Rails::Engine
155
+ # ...
156
+ initializer "my-engine.importmap" do |app|
157
+ app.config.importmap.draw(Engine.root.join("config/importmap.rb"))
158
+ end
159
+ end
160
+ end
161
+ ```
162
+
163
+ And pinning JavaScript modules from the engine:
164
+
165
+ ```ruby
166
+ # my_engine/config/importmap.rb
167
+
168
+ pin_all_from File.expand_path("../app/assets/javascripts", __dir__)
169
+ ```
92
170
 
93
171
  ## Caching the import map and preload modules
94
172
 
@@ -12,7 +12,8 @@ module Importmap::ImportmapTagsHelper
12
12
  # Generate an inline importmap tag using the passed `importmap_json` JSON string.
13
13
  # By default, `Rails.application.config.importmap.to_json(resolver: self)` is used.
14
14
  def javascript_inline_importmap_tag(importmap_json = Rails.application.config.importmap.to_json(resolver: self))
15
- tag.script(importmap_json.html_safe, type: "importmap", "data-turbo-track": "reload")
15
+ tag.script importmap_json.html_safe,
16
+ type: "importmap", "data-turbo-track": "reload", nonce: content_security_policy_nonce
16
17
  end
17
18
 
18
19
  # Include the es-module-shim needed to make importmaps work in browsers without native support (like Firefox + Safari).
@@ -20,16 +21,18 @@ module Importmap::ImportmapTagsHelper
20
21
  javascript_include_tag "es-module-shims", async: true, "data-turbo-track": "reload"
21
22
  end
22
23
 
23
- # Import a named JavaScript module using a script-module tag.
24
- def javascript_import_module_tag(module_name)
25
- tag.script %(import "#{module_name}").html_safe, type: "module"
24
+ # Import a named JavaScript module(s) using a script-module tag.
25
+ def javascript_import_module_tag(*module_names)
26
+ imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
27
+ tag.script imports.html_safe,
28
+ type: "module", nonce: content_security_policy_nonce
26
29
  end
27
30
 
28
31
  # Link tags for preloading all modules marked as preload: true in the `importmap`
29
32
  # (defaults to Rails.application.config.importmap), such that they'll be fetched
30
33
  # in advance by browsers supporting this link type (https://caniuse.com/?search=modulepreload).
31
34
  def javascript_importmap_module_preload_tags(importmap = Rails.application.config.importmap)
32
- javascript_module_preload_tag *importmap.preloaded_module_paths(resolver: self)
35
+ javascript_module_preload_tag(*importmap.preloaded_module_paths(resolver: self))
33
36
  end
34
37
 
35
38
  # 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)
data/lib/importmap/map.rb CHANGED
@@ -9,14 +9,14 @@ class Importmap::Map
9
9
  end
10
10
 
11
11
  def draw(path = nil, &block)
12
- if path
12
+ if path && File.exist?(path)
13
13
  begin
14
- instance_eval(File.read(path))
14
+ instance_eval(File.read(path), path.to_s)
15
15
  rescue Exception => e
16
16
  Rails.logger.error "Unable to parse import map from #{path}: #{e.message}"
17
17
  raise "Unable to parse import map from #{path}: #{e.message}"
18
18
  end
19
- else
19
+ elsif block_given?
20
20
  instance_eval(&block)
21
21
  end
22
22
 
@@ -0,0 +1,68 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "json"
4
+
5
+ class Importmap::Packager
6
+ Error = Class.new(StandardError)
7
+ HTTPError = Class.new(Error)
8
+ ServiceError = Error.new(Error)
9
+
10
+ singleton_class.attr_accessor :endpoint
11
+ self.endpoint = URI("https://api.jspm.io/generate")
12
+
13
+ def initialize(importmap_path = "config/importmap.rb")
14
+ @importmap_path = importmap_path
15
+ end
16
+
17
+ def import(*packages, env: "production", from: "jspm")
18
+ response = post_json({
19
+ "install" => Array(packages),
20
+ "flattenScope" => true,
21
+ "env" => [ "browser", "module", env ],
22
+ "provider" => from.to_s,
23
+ })
24
+
25
+ case response.code
26
+ when "200" then extract_parsed_imports(response)
27
+ when "404", "401" then nil
28
+ else handle_failure_response(response)
29
+ end
30
+ end
31
+
32
+ def pin_for(package, url)
33
+ %(pin "#{package}", to: "#{url}")
34
+ end
35
+
36
+ def packaged?(package)
37
+ importmap.match(/^pin "#{package}".*$/)
38
+ end
39
+
40
+ private
41
+ def extract_parsed_imports(response)
42
+ JSON.parse(response.body).dig("map", "imports")
43
+ end
44
+
45
+ def handle_failure_response(response)
46
+ if error_message = parse_service_error(response)
47
+ raise ServiceError, error_message
48
+ else
49
+ raise HTTPError, "Unexpected response code (#{response.code})"
50
+ end
51
+ end
52
+
53
+ def parse_service_error(response)
54
+ JSON.parse(response.body.to_s)["error"]
55
+ rescue JSON::ParserError
56
+ nil
57
+ end
58
+
59
+ def post_json(body)
60
+ Net::HTTP.post(self.class.endpoint, body.to_json, { "Content-Type" => "application/json" })
61
+ rescue => error
62
+ raise HTTPError, "Unexpected transport error (#{error.class}: #{error.message})"
63
+ end
64
+
65
+ def importmap
66
+ @importmap ||= File.read(@importmap_path)
67
+ end
68
+ end
@@ -1,3 +1,3 @@
1
1
  module Importmap
2
- VERSION = "0.4.2"
2
+ VERSION = "0.5.2"
3
3
  end
@@ -1,7 +1,3 @@
1
- # Use Action Cable channels (remember to import "@rails/actionable" in your application.js)
2
- # pin "@rails/actioncable", to: "actioncable.esm.js"
3
- # pin_all_from "app/javascript/channels", under: "channels"
4
-
5
1
  # Use direct uploads for Active Storage (remember to import "@rails/activestorage" in your application.js)
6
2
  # pin "@rails/activestorage", to: "activestorage.esm.js"
7
3
 
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.2
4
+ version: 0.5.2
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-12 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -24,20 +24,6 @@ dependencies:
24
24
  - - ">="
25
25
  - !ruby/object:Gem::Version
26
26
  version: 6.0.0
27
- - !ruby/object:Gem::Dependency
28
- name: httparty
29
- requirement: !ruby/object:Gem::Requirement
30
- requirements:
31
- - - ">="
32
- - !ruby/object:Gem::Version
33
- version: '0.16'
34
- type: :runtime
35
- prerelease: false
36
- version_requirements: !ruby/object:Gem::Requirement
37
- requirements:
38
- - - ">="
39
- - !ruby/object:Gem::Version
40
- version: '0.16'
41
27
  description:
42
28
  email: david@loudthinking.com
43
29
  executables: []
@@ -54,7 +40,7 @@ files:
54
40
  - lib/importmap/commands.rb
55
41
  - lib/importmap/engine.rb
56
42
  - lib/importmap/map.rb
57
- - lib/importmap/pinner.rb
43
+ - lib/importmap/packager.rb
58
44
  - lib/importmap/reloader.rb
59
45
  - lib/importmap/version.rb
60
46
  - 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