Rails 7 ./bin/importmap command not working - ruby-on-rails

I created a new Rails 7 application (rails 7.0.4 and Ruby 3.0.4) and tried to use the importmap command to create a pin entry for jquery in config/importmap.rb. The command comes back immediately and there is no entry for jquery in importmap.rb.
Here's the command I ran and what comes back in the terminal:
C:\Users\Owner\Documents\My Work\work\railsprojects\rails7a> ./bin/importmap pin jquery
C:\Users\Owner\Documents\My Work\work\railsprojects\rails7a>
Here's the contents of config/importmap.rb:
# Pin npm packages by running ./bin/importmap
pin "application", preload: true
pin "#hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "#hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "#hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
As you can see, there is no pin for jquery, which is what I expected to see in this file.
I don't understand why it's not working. Does anyone know why the importmap command is not working for me and how I can get it to work properly? Thanks.

Related

Rails, ESBuild source map is always missing, but it is in the build

ActionController::RoutingError (No route matches [GET] "/assets/application.js-1246371c75312771378dc97fa604ef404c73f9b477b5eb8f4c6ebb2fd2e1e323.map"):
My build script in package.json is:
"build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds",
So I see under assets, under builds, my application.js, and my application.js.map
But developer console shows 404 on the source map, and the server logs show that resource as an error. What am I doing wrong?
Corresponding to this thread
Setting config.assets.debug = false will solve that error
The config.assets.debug = false workaround has undesirable side effects. Missing debug log messages etc.
A cleaner solution is to add the following route definition to config/routes.rb:
if Rails.env.development?
redirector = ->(params, _) { ApplicationController.helpers.asset_path("#{params[:name].split('-').first}.map") }
constraint = ->(request) { request.path.ends_with?(".map") }
get "assets/*name", to: redirect(redirector), constraints: constraint
end
This resolves the sourcemaps for JS and CSS files and keeps asset debugging intact.

Ruby on Rails (Agile book example) error: Webpacker::Manifest::MissingEntryError in Store#index

Please note that I am a beginner in Ruby on Rails and here. This seems to me like a near repeat of other not-resolved questions such as Webpacker::Manifest::MissingEntryError in .... localhost:3000/* errors but I was asked to repost it as a new thread:
I am working through the depot examples in Agile Web Development with Rails 6, but there is a consistent error when dealing with \app\views\layout\application.html.erb when it encounters
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
Showing /Users/rogerburks/Documents/rubyVacation/depot2/app/views/layouts/application.html.erb where line #9 raised:
Webpacker can't find application in /Users/rogerburks/Documents/rubyVacation/depot2/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
This is happening in development and occurs when I load the views in localhost:3000. I have faced the same error over 3 days of trying to fix it as a new Agile reader, even creating new projects and starting over. Having tried to explore the 4 presented options as best I can, and having googled the error and tried some attempted solutions, I decided that it would be far more efficient for me to ask here rather than to continue flailing.
I suspect that my project is being built in a way that breaks it. This describes the issue without telling how to fix it: 4. Your webpack configuration is not creating a manifest.
I suspect that I may have either installed a webpacker that is too new for my configuration, or I have not properly installed a dependency. Either way, Rails does not generate something that will work with the book's examples.
config/webpacker.yml looks like this:
default: &default
source_path: app/javascript
source_entry_path: packs
public_root_path: public
public_output_path: packs
cache_path: tmp/cache/webpacker
check_yarn_integrity: false
webpack_compile_output: true
compile: true
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
resolved_paths: []
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
# Extract and emit a css file
extract_css: false
static_assets_extensions:
- .jpg
- .jpeg
- .png
- .gif
- .tiff
- .ico
- .svg
- .eot
- .otf
- .ttf
- .woff
- .woff2
extensions:
- .mjs
- .js
- .sass
- .scss
- .css
- .module.sass
- .module.scss
- .module.css
- .png
- .svg
- .gif
- .jpeg
- .jpg
development:
<<: *default
compile: true
# Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
check_yarn_integrity: true
# Reference: https://webpack.js.org/configuration/dev-server/
dev_server:
https: false
host: localhost
port: 3035
public: localhost:3035
hmr: false
# Inline should be set to true if using HMR
inline: true
overlay: true
compress: true
disable_host_check: true
use_local_ip: false
quiet: false
pretty: false
headers:
'Access-Control-Allow-Origin': '*'
watch_options:
ignored: '**/node_modules/**'
test:
<<: *default
compile: true
# Compile test packs to a separate directory
public_output_path: packs-test
production:
<<: *default
# Production depends on precompilation of packs prior to booting for performance.
compile: false
# Extract and emit a css file
extract_css: true
# Cache manifest.json for performance
cache_manifest: true
I had the bright idea run the book's downloadable example folder separately, since in general the downloaded examples work.
After editing the project's gemfile to help it recognize that I am using Ruby 2.7.2 instead of Ruby 2.6.5, I ran
gem install bundler and then bundle install and then I started the server. Somehow, the project itself now runs.
My next task is to figure out why it works. The file webpacker.yml only differs in that I had added compile: true to the default configuration while flailing, which probably did not break anything. This eliminates settings in this file as a possible cause.
Incidentally, this also "solves" the problem in that it provides a set of steps that can lead to a solution in this specific case. It does not explain exactly why the problem occurred, but most likely I would find that some dependency was not installed right.

Select2 Css is not loading via yarn or assets precompile

I am running into a strange issue where everything is working as expected except select2. I am having Rails 6.0.0 app and installed select2 via yarn add select2.
Then i added it to application.js file. File looks like below.
#app/javascripts/packs/application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
require('datatables.net')
require('datatables.net-dt')
require('datatables.net-bs4')
require('select2')
import "bootstrap"
import 'popper.js/dist/popper.js';
import $ from 'jquery';
global.$ = jQuery;
import "chart.js"
import 'select2'; // globally assign select2 fn to $ element
import 'select2/dist/css/select2.css'; // optional if you have css loader
document.addEventListener("turbolinks:load", () => {
setTimeout(function() {
$('.success, .alert').fadeOut();
}, 10000);
})
Right now it looks like this
select2 dropdown box
When I go to Source tab in chrome developer tools, it shows only select2/dist/js folder under node_modules. I have tried precompiling and clobbering the assets but not working. The whole this is running fine in my local, only causing issue in production server.
Edit:
My production.rb
https://gist.github.com/rajanhcah/3ee13925b0ae305a6fe2c64013ab6534
If you're including CSS in app/javascripts/packs/application.js, make sure that app/views/layouts/application.html.erb is also using the stylesheet_pack_tag (see the "Usage" section in the webpacker doc).
Otherwise, if you have stylesheet_link_tag, you can use the classical app/assets/stylesheets/application.css.
# app/assets/stylesheets/application.scss
#import 'select2/dist/css/select2';

What is the best way to use webpacker in a Rails engine?

I realise there is some debate about using webpacker in Rails engines but I have a simple usecase and currently have a workaround. Would like to know of a better (the best?) solution.
In this rails engine I have webpacker setup in the "spec/dummy" directory and everything works well in dev:
https://github.com/RealEstateWebTools/property_web_scraper/tree/master/spec/dummy/config/webpack
When the engine is used by a rails app however it will not find the compiled webpack files so each time I have a release ready I compile the webpack files and manually copy them to the vendor directory:
https://github.com/RealEstateWebTools/property_web_scraper/tree/master/vendor/assets/javascripts
I then require that file here:
https://github.com/RealEstateWebTools/property_web_scraper/blob/master/app/assets/javascripts/property_web_scraper/spp_vuetify.js
In my layout I use the above file using the good old sprockets "javascript_include_tag": https://github.com/RealEstateWebTools/property_web_scraper/blob/master/app/views/layouts/property_web_scraper/spp_vuetify.html.erb
In the layout there is a check to see if I'm running the "spec/dummy" app in which case I will user webpacker as it would normally be used in dev.
There must be a better way than this.
Webpacker has been retired
https://github.com/rails/webpacker
Going forward, it's better to switch to jsbundling-rails with webpack.
(I would rather suggest esbuild as it's "10×-100× faster")
But let's do it with webpack:
rails new webpack-in-engine --javascript webpack --css tailwind --database postgresql
In app/javascript/application.js I do:
console.log("hello from application.js")
And it works.
Now with an engine:
rails plugin new admin --mountable
Then depends:
Separate JS
Add an entry to your webpack.config.js:
const path = require("path")
const webpack = require("webpack")
module.exports = {
mode: "production",
devtool: "source-map",
entry: {
application: "./app/javascript/application.js",
admin: "./admin/app/javascript/admin.js"
},
output: {
filename: "[name].js",
sourceMapFilename: "[name].js.map",
path: path.resolve(__dirname, "app/assets/builds"),
},
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
]
}
<%= javascript_include_tag "admin", "data-turbo-track": "reload", defer: true %>
Shared JS
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
And in your app/javascript/application.js:
import "./../../admin/app/javascript/admin"
See full repo https://github.com/dorianmariefr/webpack-in-engine
Aside: Also I would rather namespace in the main app than have engines. I think engines are for very specific use cases not namespacing.

javascript_include_tag Rails 4 generating "/javascripts/" instead of "/assets" in production

I have a Rails 4 application with
<%= javascript_include_tag "modernizr", "data-turbolinks-track" => true %>
in the head. In development, the following HTML is rendered, and modernizr is loaded:
<script data-turbolinks-track="true" src="/assets/modernizr.js?body=1"></script>
In production, the followign HTML is rendered, and modernizr is not loaded (404 not found):
<script data-turbolinks-track="true" src="/javascripts/modernizr.js"></script>
In production, /assets/modernizr.js is found and browsable.
The Rails documentation says that the javascript_include_tag should generate
<script data-turbolinks-track="true" src="/assets/modernizr.js?body=1"></script>
In production, my stylesheet_link_tags are fine, linking to the /assets/ directory.
Why is the javascript_include_tag linking to /javascripts instead of /assets in production, and how can I fix it?
One of the usage statements for AssetUrlHelper indicates it will produce /javascripts/ urls
like what you are seeing:
# asset_path "application", type: :javascript # => /javascripts/application.js
(from asset_url_helper.rb line 117 - [1])
This code looks like it can only be reached if the precompiled asset is missing
so it would appear that your asset compilation is not working (my deployments usually
fail when that happens, so maybe yours isn't even firing).
The same asset_url_helper.rb calls the /javascripts/ part 'extname' and
uses the following map to know how to generate the name:
# Maps asset types to public directory.
ASSET_PUBLIC_DIRECTORIES = {
audio: '/audios',
font: '/fonts',
image: '/images',
javascript: '/javascripts',
stylesheet: '/stylesheets',
video: '/videos'
}
A new Rails 4 app has this in the config/environments/production.rb
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
which seems to match the behavior you are seeing.
By default, Rails only precompiles application.js, application.css and any images it finds in the assets path. Therefore, in production mordernizr will not get precompiled and thus the javascript helpers will not be able to find the file.
In order to fix the issue, you can add modernizr to the precompile list by modifying the following config in production.rb
config.assets.precompile += ['modernizr.js']
For more information see the Rails Guides
Be sure to precompile your assets in production by running this command:
RAILS_ENV=production bundle exec rake assets:precompile
The Rails Guide on the asset pipeline can give you more details: http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets
I have a new application using Rails 4 deployed on Heroku with :
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
my javascript application.(fingerprint).js called from the src: assets/application.js
i think your problem come from something into your production.rb who define assets from another location.
So maybe you can add Moderniz.js to
config.assets.precompile = ['.js', '.css', '*.css.erb']
in config/production.rb
Or simply require modernizr script into your application.js
//= require mordernizr
and remove the modernizr script call into your layout.
<%= javascript_include_tag "modernizr", "data-turbolinks-track" => true %>
Can you check from where your application.js is served into your production environment ?
It may be because this file needs to be in /vendor/assets/javascript instead of /app/assets/javascript. The Vendor folder is for javascript libraries, and the App folder is for your code.
A better solution than adding a tag to your layout would be adding a script reference to your application.js and let the sass compiler compress and attach it to your main javascript file.
If you don't get a definitive answer, check out:
http://guides.rubyonrails.org/asset_pipeline.html#asset-organization

Resources