Selective Rails 3.2 asset pipeline compression per file

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

I'd like to selectively compress some of the javascript files in a Rails 3.2 app, but still have all js assets served from a single bundled file in the production environment.

Syntax like this, inside of the app/assets/javascripts/application.js file, using the made-up :compress => false option passed to the last 3 sprockets require directives I hope explains what I'm trying to achieve.

// Contents of app/assets/javascripts/application.js // //= require jquery //= require jquery_ujs //= require angular-1.0.1/angular, :compress => false //= require angular-1.0.1/angular-resource, :compress => false //= require products, :compress => false 

So jquery.js and jquery_ujs.js files will be compressed (by Rails asset compilation, which uses UglifierJS by default), and the remaining 3 files will not be compressed, but they will be bundled into the application.js bundle.

Is there any way available to do this?

The motivation is that the products.js file contains an angularjs controller that makes use of angular's dependency injection which requires specific variable names such as $scope and $http are not altered.

回答1:

I'm using this line in my config/environment/production.rb file

config.assets.js_compressor = Sprockets::LazyCompressor.new { Uglifier.new(:mangle => false) }

It compress my controllers but it doesn't change method signatures so DI still works as expected.



回答2:

To get this to work with Rails 4 since it uses a newer version of sprockets I used:

config.assets.js_compressor = Uglifier.new(mangle: false) if defined? Uglifier

in environments/production.rb



回答3:

Note that for this specific reason there's an option to specify the injected services with strings rather than variable names. See the line under the controller.

var MyController = function(renamed$scope, renamedGreeter) {   ... } MyController.$inject = ['$scope', 'greeter']; 

Example taken from http://docs.angularjs.org/guide/di



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!