简体   繁体   中英

Creating a common javascript function in the Rails Asset Pipeline

I have a Rails app with the following javascript asset structure

|- app
  |- assets
    |- javascripts
      |- articles
        - index.js
        - show.js
      - application.js

The application.js file seems to be a manifest of all files

//= require jquery
//= require jquery_ujs
//= require react
//= require react_ujs
//= require_tree .

Let's say I have some common function foo() that I want to be accessible globally (from both index.js and show.js )

function foo() {
  // do cool stuff here
}

How do i go about creating a common JS file with common/shared functions like this? Specifically, where should the file be created and how should it be incorporated into the manifest? And how will it be compiled when compiling assets in production?

Thanks!

You can make new file called common.js and require it before index.js and show.js in manifest file

app/assets/javascripts/common.js

function foo() {
  // do cool stuff here
}

app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require react
//= require react_ujs
//= require common
//= require_tree .

The order of assets precompile will follow the order of your manifest file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM