8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

既存のJavaScript + importmap で動かす備忘録

Posted at

既存のJavaScript app/assets/javascripts/
Importmapに対応したJavascript app/javascript/ の共存、その備忘録になります。

ここでは、js_compressor にTerserを利用しています。

Gemfile

Gemfile
...

# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"

# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"

# Terser minifies JavaScript files by wrapping TerserJS to be accessible in Ruby [https://rubygems.org/gems/terser]
gem 'terser', '~> 1.1', '>= 1.1.8'

...

environment

config/environments/production.rb
# Compress JavaScripts and CSS.
config.assets.js_compressor = Terser.new(compress: { drop_console: true })

Javascript

application.js リネーム

app/assets/javascripts/, app/javascript/ 2箇所にapplication.js ファイルが存在するとエラーとなるため、application_old.js にリネームしています。

require 指定

require_directory, require_tree 等、環境に合わせて調整してください。

app/assets/javascripts/application_old.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//

//= require_directory .
app/javascript/application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails

import Rails from "@rails/ujs";
Rails.start();

Layout

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all' %>
-   <%= javascript_include_tag 'application' %>
+   <%= javascript_include_tag 'application_old' %>
+   <%= javascript_importmap_tags %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

最後に

同じケースにTryしている方のヒントになれば幸いです。
もっと良い方法が見つかりましたらアップデートしていきたいと思います。

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?