Keith Carter
Keith Carter

Reputation: 456

How to share variables and functions across multiple client side JavaScript files with Webpacker in Rails 6?

Webpacker packs files like so

(function(module, exports) {

  function myFunction() {...}

a consequence of this is that functions and variables from one file are not accessible from another. Or the console.

What's the "rails way" to address this?

Upvotes: 3

Views: 1094

Answers (2)

Adim
Adim

Reputation: 1776

Once you move over to Webpacker, you can write your Javascript with modern ES6. This way, we can export and import modules in conventional ES6.

E.g:

// app/javascript/some_module.js

import moment from 'moment';

const SomeModule = {
  someMethod() {
    return someResult;
  }
};

export default SomeModule;

And you can now import this into another module:

// app/javascript/another_module.js

import SomeModule from './some_module';

SomeModule.someMethod();

Notice the folder structure as comments in the file.

Upvotes: 4

Dijkie85
Dijkie85

Reputation: 1106

You could load the required variables/functions as Webpack plugins using environment.plugins.append in your `config/webpack/environment.js' file.

So, for example, if you wanted to expose $ and jQuery functions from the jQuery module, the file would look like this:

#config/webpack/environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack');

environment.plugins.append('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
)

Hope it helps!

Upvotes: 0

Related Questions