Rails 3.1 asset pipeline and manually ordered Javascript requires

前端 未结 5 1998
余生分开走
余生分开走 2020-11-29 01:01

I am trying to convert an existing app to the new 3.1 asset pipeline layout, and want to include a lot of vendor files that have to be in a specific order, (underscore.js an

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 01:17

    My answer applies to Rails 3.1rc4, I don't know whether it functions the same with other versions.

    You can actually put all require statements in app/assets/javascripts/application.js whether or not the .js files are in app/assets/javascripts/ or vendor/assets/javascripts/

    Like so:

    // this is in app/assets/javascripts/application.js
    
    //= require modernizr-2.0
    //= require jquery
    //= require jquery_ujs
    //= require jqueryui-1.8.12
    //= require jquery.easing-1.3
    //= require jquery.noisy
    //= require jquery.jslide-1.0
    //= require respond
    //= require smoke
    //= require_tree
    

    I included require_tree here because I have other javascript files for my individual controllers (pages.js.coffee, users.js.coffee) and a general one for site-wide stuff (site.js.coffee)

    Meanwhile here's the file structure.

    app/
    ├── assets
    │   ├── javascripts
    │   │   ├── application.js
    │   │   ├── pages.js.coffee
    │   │   ├── users.js.coffee
    │   │   └── site.js.coffee
    │   └── stylesheets
    └── plugins
    
    vendor/
    ├── assets
    │   ├── javascripts
    │   │   ├── jquery.easing-1.3.js
    │   │   ├── jquery.jslide-1.0.js
    │   │   ├── jquery.noisy.js
    │   │   ├── jqueryui-1.8.12.js
    │   │   ├── modernizr-2.0.js
    │   │   ├── respond.js
    │   │   └── smoke.js
    │   └── stylesheets
    └── plugins
    

    This allows me to control the load order of vendor libraries (which matters a lot, usually) and not worry about my internal javascript, where order generally matters less.

    More importantly, I control all require statements within one often used file, I find that both safer and cleaner.

提交回复
热议问题