Rails:从 webpacker 提供的文件访问 JS 模块方法 [英] Rails: Accessing JS module methods from files served by webpacker
问题描述
我尝试使用 Webpacker gem 将我们应用程序中的资产移动到 webpack.应用程序很大,所以我需要做一部分.
I try to move assets in our application to webpack using Webpacker gem. Application is very big, so I need to do it partially.
我成功地使用 javascript_pack_tag
我导出了一个超级简单的模块:
I export a super simple module:
# javascript/src/javascript/test.js'
const Direction = {
log_to_console: function(){
console.log('test');
}
};
export default Direction;
然后在应用入口点导入
# javascript/packs/application.js
import Test from '../src/javascript/test.js'
Test.log_to_console();
最终在布局中渲染它:
# app/views/application.slim
= javascript_include_tag 'application'
结果是:测试"字符串在浏览器控制台中可见.
The result is: "Test" string visible in the browser console.
目前在整个应用程序中,我们在这样的视图中使用模块:
Currently in the whole application we use Modules in views like this:
# app/views/assets/javascripts/test.coffee
log_to_console = ->
console.log('test');
@Test = { log_to_console }
# app/views/some/template.slim
javascript:
Test.log_to_console()
但是在将模块移至 webpack 后,我无法再访问 Test
模块.
But after moving module to webpack I can't access the Test
module anymore.
所以我的问题是:
如何配置 webpacker
gem 或重构上面的代码以使 log_to_console()
方法在视图/浏览器检查器中可用?
How to configure webpacker
gem OR refactor the code above to make the log_to_console()
method available in views/browser inspector?
理想情况下,我们也可以在由链轮编译的旧 javascript 文件中访问它们.
Ideally it would be if we could also access them in old javascript files compiled by sprockets.
推荐答案
我现在想出了那个解决方案.可能对遇到该问题的任何人都有帮助.
I figured out that solution for now. May be helpful for anyone that encounters that problem.
如果有人找到更好的解决方案,我很高兴在这里看到它;)
If anyone finds better solution, I would be glad to see it here ;).
对于现在需要在视图/其他咖啡文件中可见的所有模块/库,我只是通过 window
对象设置为全局可用.
For now all our modules/libraries that are needed to be visible in views/other coffee files, I just set as globally available via the window
object.
import Foo from '../src/javascript/foo.js
window.Foo = Foo
我知道这是一个丑陋的反模式,但在我们更新我们的脚本之前作为临时解决方案效果很好.
I know it's ugly anti pattern, but works well as temporary solution until we update our scripts behave more like independent packs.
这篇关于Rails:从 webpacker 提供的文件访问 JS 模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!