简体   繁体   English

在Rails Asset Pipeline中创建通用的javascript函数

[英]Creating a common javascript function in the Rails Asset Pipeline

I have a Rails app with the following javascript asset structure 我有一个具有以下javascript资产结构的Rails应用程序

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

The application.js file seems to be a manifest of all files application.js文件似乎是所有文件的清单。

//= 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 ) 假设我有一些通用函数foo() ,希望可以全局访问(从index.jsshow.js

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

How do i go about creating a common JS file with common/shared functions like this? 如何使用这样的通用/共享功能创建通用JS文件? 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 您可以创建一个名为common.js新文件,并在清单文件中的index.jsshow.js之前要求它

app/assets/javascripts/common.js 应用程序/资产/ JavaScript的/ common.js

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

app/assets/javascripts/application.js 应用程序/资产/ JavaScript的/ 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. 资产预编译的顺序将遵循清单文件的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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