Seb Wilgosz
Seb Wilgosz

Reputation: 1250

Rails: Accessing JS module methods from files served by webpacker

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.

Upvotes: 4

Views: 1814

Answers (1)

Seb Wilgosz
Seb Wilgosz

Reputation: 1250

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.

Upvotes: 2

Related Questions