importmap-rails 0.4.1 → 0.5.1

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: 3e7f034e1cb0febd2ab7dfd1b1422fd2b717368ea4e64e86a49ac2d92ba0db7c
4
- data.tar.gz: 20a6b4114ccf1ee891f2ad255e70f50f8135421d6f1f1eeb68b6f73cd44d165a
3
+ metadata.gz: 80b9cda4f79989099769db06ef9eeb785a7f9906cfa9eacbd3d6bf1dcd437edd
4
+ data.tar.gz: 77972151d15109c1ee373331fa71f42e3957afb97af470fb8683f2c7e027df73
5
5
  SHA512:
6
- metadata.gz: 3eb40a5e05dd1541dcc53f69bb4610469a847f3a1a69591af02e002fb435627ef1b7173685a94db22936c6c50c5f5d2abcc3ea97508d3a06462ac80eb4354292
7
- data.tar.gz: abe96793497d1ebedf3d0fc4a6ca4c8abe69f4e087a5df835a86dbc95c5c9ac13246aefa06ca92bdcd97d4647aa83cdccc4b9f69b27304c96bec074456236c11
6
+ metadata.gz: 5a1c26adbcb471b81dcd1504771f36ac73dfb542a41c379dd257f01a6ec633545030ea0a4d33d49ff40fe56f30c336a0cee8e990aa58f1a3088acf7f0738c46b
7
+ data.tar.gz: d1c94f03f8c844303887d08af37028e78b667120ce7fa04cbf3c7d7c52b1f56bd10ba69ed9ce0de8ea8b6af234443f96c03c0a3da21d2e0ba301a7997b00ecd4
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)
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
14
  instance_eval(File.read(path))
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.1"
2
+ VERSION = "0.5.1"
3
3
  end
@@ -1,20 +1,6 @@
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
 
8
- # Pin vendored modules by first adding the following to app/assets/config/manifest.js:
9
- # //= link_tree ../../../vendor/assets/javascripts .js
10
- # pin_all_from "vendor/assets/javascripts"
11
-
12
- # JavaScript CDN provider. Also available: :jsdelivr, :esmsh, :unpkg, :skypack
13
- provider :jspm
14
-
15
- # Use NPM libraries from CDN
16
- # pin "local-time", version: "2.1.0", file: "app/assets/javascripts/local-time.js"
17
- # pin "vue", version: "2.6.14", file: "dist/vue.esm.browser.js", from: :jsdelivr
18
- # pin "d3", version: "7.0.1", file: "?bundle", from: :esmsh
4
+ # Use node modules from a JavaScript CDN by running ./bin/importmap
19
5
 
20
6
  pin "application"
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.1
4
+ version: 0.5.1
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-06 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