RequireJS concatenating JS but not minifying - javascript

I'm using requirejs-rails version 0.9.8 on Rails 4.0.13. I'm running into an issue where requirejs is concatenating all of my JS files, but not minifying them.
Here's my requirejs.yml file:
paths:
'react' : 'react/react-with-addons'
'react-dom' : 'react/react-dom'
'react-router' : 'react-router/index'
'react-router-shim' : 'react-router-shim/react-router-shim'
'jquery' : 'jquery/dist/jquery'
'lodash' : 'lodash/lodash'
'flux' : 'flux/dist/Flux'
'es6-promise' : 'es6-promise/promise'
'event-emitter' : 'eventemitter2/lib/eventemitter2'
'object-assign' : 'object-assign/object-assign'
'async' : 'requirejs-plugins/src/async'
'moment' : 'moment/min/moment-with-locales.min'
'bootstrap' : 'bootstrap/bootstrap.min'
'material' : 'material-kit/material.min'
'material-kit' : 'material-kit/material-kit'
'jquery' : 'jquery/jquery.min'
shim:
'react-router-shim':
exports: 'React'
'react-router':
deps: ['react-router-shim']
exports: 'ReactRouter'
'material-kit':
deps: ['jquery', 'material', 'bootstrap']
'material':
deps: ['jquery', 'bootstrap']
'bootstrap':
deps: ['jquery']
exports: 'jquery'
'lodash':
exports: '_'
'object-assign':
exports: 'ObjectAssign'
And after running rake assets:precompile RAILS_ENV=production, I look into public/assets for the application-HASH file and see that it's just a big file with all of the JS concatenating. Here's my production.rb file as well:
App::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.1'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
EDIT
It looks like requirejs-rails is successfully minifying my JS files individually in my app's tmp/requirejs/dst directory, but these files aren't joined together to create the application-HASH.js file.

I found the issue.
There was a syntax error with my JavaScript source that was silently failing the build. It was only when I added logLevel: 0 to my requirejs.yml file that I was able to see the error Unexpected token operator «=», expected punc «,» (line: 11, col: 37, pos: 276).

Related

How to solve a problem with 'Cross-Origin Request Blocked'?

I've got a problem with:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://{myDomain}:3000/api. (Reason: CORS request did not succeed).
What I'm trying to do here is to pass a longitude and a latitude from a client-side javascript into a node.js on a server-side. I'm using express and fetch.
This app app is working on my VPS. I also have a domain with SSL aliases.
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
latitude: <span id="latitude"></span>°<br />
longitude: <span id="longitude"></span>°<br />
</p>
<button id="geolocate">geolocate</button>
<script src="main.js"></script>
</body>
</html>
My main.js:
document.getElementById('geolocate').addEventListener('click', event => {
if ('geolocation' in navigator) {
console.log('geolocation available');
navigator.geolocation.getCurrentPosition(position => {
var x = position.coords.latitude;
var y = position.coords.longitude;
console.log(x, y);
document.getElementById('latitude').textContent = x;
document.getElementById('longitude').textContent = y;
const data = {x, y}
const options = {
method: 'POST',
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
}
}
fetch('https://{myDomain}:3000/api', options);
});
} else {
console.log('geolocation not available');
}
});
Below my node.js code:
const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next()
});
app.post('/api', (req, res) => {
console.log(req);
});
To run my node.js I use nodemon.
On my VPS I use centOS7. Below is my httpd log:
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used. If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin#your-domain.com
#
ServerAdmin root#localhost
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory "/var/www/wet-pogotowie.pl/html">
AllowOverride none
Require all denied
Header set Access-Control-Allow-Origin "*"
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/wet-pogotowie.pl"
#
# Relax access to content within /var/www.
#
<Directory "/var/www/wet-pogotowie.pl/html">
AllowOverride None
Require all granted
Header set Access-Control-Allow-Origin "*"
</Directory>
# Further relax access to the default document root:
<Directory "/var/www/wet-pogotowie.pl/html">
Header set Access-Control-Allow-Origin "*"
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
Require all denied
</Files>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
#CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>
#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
AllowOverride None
Options None
Require all granted
</Directory>
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig /etc/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
</IfModule>
#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default. To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8
<IfModule mime_magic_module>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
MIMEMagicFile conf/magic
</IfModule>
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
IncludeOptional sites-enabled/*.conf
I have a problem with this header: <dictionary><dictionary/> Header set Access-Control-Allow-Origin "*"
Could you guys help me?
BTW I asked this question already here: A problem with a post method (using fetch and express) but I didn't get an answer.

Rails 4 - In production my javascript is loaded but does not work while it works well in development

I work with :
Rails version 4.2.3
Ruby version 2.2.1
I have managed to run my application in production doing these steps :
rake db:create RAILS_ENV=production
rake db:migrate RAILS_ENV=production
rake assets:precompile and rake assets:precompile RAILS_ENV=production
I had some troubles with my application.js and application.css files because all the require were not in the right orders. I had to put require_tree at the bottom and require jquery at the top directly followed by require jquery_ujs.
Now my files are the following :
application.js file :
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require dataTables/jquery.dataTables
//= require dataTables/extras/dataTables.tableTools
//= require_tree .
application.css file :
/*
*= require_self
*= require bootstrap
*= require dataTables/jquery.dataTables
*= require_tree .
*/
production.rb file :
Rails.application.configure do
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
config.force_ssl = false
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
development.rb file :
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Do not compress assets
# config.assets.compress = false
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
However all the javascript that I wrote is not working in production. I looked into my browser consol and my javascript is loaded I can see it in the DOM when I right click "inspect element".
So why my javascript works in development but is not working in production ?
I tried several options :
1st try : I add the line config.assets.precompile += %w( *.css *.js)
2nd try : config.assets.precompile += %w( *.css *scss *.js)
3rd try : I found that in config/initializers/assets.rb was a line of code very similar to what I tried in my 1st and 2nd try so I enabled this line of code in config/initializers/assets.rb : Rails.application.config.assets.precompile += %w( search.js ) but I still have nothing.
4th try : I read in another post on Stackoverflow that removing in my GemFile jquery-ui-rails could work but I still have no javascript
Here is my GemFile :
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
#To have charts on rails
gem 'chartkick'
#Turn into pdf
gem 'pdfkit'
#To read, write spreadsheets
gem 'spreadsheet', '~> 1.0.3'
#To import CSV file and spreadsheets
gem 'roo', '~> 2.1.0'
#To improve tables style
gem 'jquery-datatables-rails', '~> 3.3.0'
gem 'jquery-ui-rails'
#Pour qu'il fonctionne, le gem bcrypt doit être utilisé sous sa version 3.1.9
gem 'bcrypt', '~>3.1.7'
gem 'bootstrap-sass', '3.2.0.0'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
#gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Would anyone have an idea about what's happening ? Why my javascript is not working in production but works well in development ?
In production mode, it should server by web servers(Apache, Nginx) and will work. until that fix you can load all files in production rather loading a compressed single application.js and application.css file. For that in production.rb file disable the config variable. like below
config.serve_static_assets = false
The problem lies within your application.js and more specifically I believe where your bootstrap is being called. What fixed it for me was moving bootstrap to the bottom.
Asset pipeline is disabled in dev which is why you did not experience the same issues there.

Rails Application Not Loading All javascript files production

I am working on a personal website Hosted in AWS. Using Ruby 1.9.3 Rails 4.1.0beta1. When I run the code locally, it works like a charm. However when I push to AWS, its missing either some JS files or some CSS files. I think it is missing JS files because if I remove the following from application.js
//= require_tree .
I can reproduce the issue locally.
Here is my Gem file:
source 'https://rubygems.org'
ruby '1.9.3'
#ruby-gemset=danielhamiltondotcom_rails_4_0
gem 'rails', '4.1.0.beta1'
group :development, :test do
gem 'rspec-rails', '2.13.1'
end
group :test do
gem 'selenium-webdriver', '2.35.1'
gem 'capybara', '2.1.0'
end
gem 'sass-rails', '4.0.1'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.1'
gem 'jquery-rails', '3.0.4'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
gem 'rails_12factor', '0.0.2'
end
Here is my production.rb file:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
#config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
config.assets.paths << Rails.root.join('app','assets','font')
config.assets.precompile += %w(.svg .eot .woff .ttf)
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
end
Here is a snippet of the html.erb page.
<%= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => false %>
<%= javascript_include_tag "application", "data-turbolinks-track" => false %>
I can't quite figure out which files are missing. Please let me know if you need more information. I have been looking around all over and haven't been able to resolve this issue.
I have tried this: Rails 4: assets not loading in production.
I was able to resolve this issue:
1) I had an extra ) in my css file. I removed that to address the compile error that AWS was giving.
2) In my Application.js file I manually required all JS files needed instead of just using the tree:
//= require jquery
//= require modernizr
//= require bootstrap
//= require jquery.fitvids
//= require jquery.easing.1.3
//= require twitter
//= require jquery.fancybox.pack
//= require jquery.fancybox-thumbs
//= require jquery.fancybox-media
//= require stellar
//= require nicescroll.min
//= require jquery.isotope.min
//= require custom
//= require custom-home
//= require portfolio
//= require jquery.flexslider
//= require retina
3) I added gem 'sprockets', '2.8' to my GemFile which i had previously omitted.
Try
RAILS_ENV=production bundle exec rake assets:precompile
Also check your prod server and make sure the asset files are there under public.

Jquery not working after precompile

An image was causing a problem on my heroku app so I changed config.assets.compile = false to config.assets.compile = true in production.rb. I then ran rake assets:precompile and pushed to the heroku server. Jquery works fine on the app website, but no longer works on my local copy. No errors are thrown in the javascript console. Here are some important files as they stand now.
Production.rb
Nonogrammed::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
Application.js
//= require jquery
//= require jquery_ujs
//= require jquery.ui.core
//= require jquery.ui.widget
//= require jquery.ui.mouse
//= require jquery.ui.draggable
//= require twitter/bootstrap
//= require_tree .
$(function() {
$( "#draggable" ).draggable({ handle: "#handle" , containment: [0,0,1200,1000] , cursor: "crosshair" });
});
UPDATE: This was caused by deleting an image , making a new image with the same name, and then pushing to heroku. Don't do that!
There's no need to precompile on your local. Sprockets automatically compiles static asset at server start.
To resolve things, delete the compiled files in the public/assets directory, commit your changes, then deploy to Heroku again.
Then, in Heroku, compile your assets by running the following from your command line:
# from command line via the Heroku Toolbelt
rake run assets:precompile
Your local assets will compile on server start (thus rendering jQuery usable again), and your assets on Heroku will be precompiled to the public/assets directory as they should be.
UPDATE:
You may need to clear your browser cache to ensure that the updated asset path is loaded into your markup.

Rails Heroku Precompiled Assets Not Loading JS?

I'm setting up my Rails app on Heroku, and running into a problem where all my CSS assets are loaded but none of my JS assets are. I'm using memcached, and followed these instructions: https://devcenter.heroku.com/articles/rack-cache-memcached-rails31.
One thing I noticed is that when I change config.assets.compile to "true" in my production.rb file, all the JS is loaded successfully but obviously the initial load of the site is tremendously slow. How can I troubleshoot this problem? I'm new to Heroku, so am unsure and haven't found anything online that is helpful.
I assume that since all my JS files are in /assets/javascripts/, that the should be included automatically, but it seems as if they're not.
Here's my production.rb:
BrainDb::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
client = Dalli::Client.new
config.action_dispatch.rack_cache = {
:metastore => client,
:entitystore => client,
:allow_reload => false
}
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
config.static_cache_control = "public, max-age=2592000"
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
I also removed everything from public/assets so it would precompile. Here's application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module BrainDb
class Application < Rails::Application
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
config.active_record.whitelist_attributes = true
config.assets.initialize_on_precompile = false
# Enable the asset pipeline
config.assets.enabled = true
config.cache_store = :dalli_store
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
UPDATE
Application.js:
//
//= require jquery
//= require jquery_ujs
Add
//= require_tree . at last and precompile
in your application.js.

Categories