Rails: Accessing JS module methods from files served by webpacker

ε祈祈猫儿з 提交于 2019-12-12 12:26:00

问题


Context

I try to move assets in our application to webpack using Webpacker gem. Application is very big, so I need to do it partially.

What did so far...

I successfully managed to call the script using 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;

Then import it in the application entry point

# javascript/packs/application.js
import Test from '../src/javascript/test.js'
Test.log_to_console();

Finally rendering it in the layout:

# app/views/application.slim
= javascript_include_tag 'application'

The result is: "Test" string visible in the browser console.

The problem

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()

But after moving module to webpack I can't access the Test module anymore.

So my question is:

How to configure webpacker gem OR refactor the code above to make the log_to_console() method available in views/browser inspector?

Ideally it would be if we could also access them in old javascript files compiled by sprockets.


回答1:


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 ;).

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.



来源:https://stackoverflow.com/questions/50414220/rails-accessing-js-module-methods-from-files-served-by-webpacker

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