0

I have used the react-rails gem for a while. While using it, I placed my ES6 components under app/assets/javascript/components folder and placed plain old JavaScript files to app/assets/javascript. The good thing was I was able to easily refer the objects of old style Javascript files from the ES6 components.

After migrating to webpacker gem, I tried to keep similar approach. I placed the modules under app/javascript/packs and placed old style JavaScript files unde app/javascript folder.

I guess, with webpack in place I have to use import / export mechanics but that I could not achieved either.

So my question is how can I use old javascript files and refer the objects inside them, within components.

For example the content of a dummy global_data.js file that reside in app/javascript directory is as follows:

function globalData (){
}
globalData.prototype.data = {};
var g_GlobalData = new globalData();

What is the ES6 way to use g_GlobalData variable within components?

Mehmet Kaplan
  • 1,723
  • 2
  • 20
  • 43
  • Export `g_GlobalData`? – evolutionxbox Nov 27 '17 at 16:54
  • Followed by `import g_GlobalData from 'path/to/g_GlobalData.js';` in the file you want to consume it with – Ted Nov 27 '17 at 16:57
  • evolutionxbox and @Ted, thanks this is the obvious thing to do. I had also done export and import previously but in that case the "data" attribute which was initiated at line 3 is not seen. That is why I thought something else could possibly be the solution. (Briefly, when I refer ```g_GlobalData.data```, I get "undefined" in export / import case.) – Mehmet Kaplan Nov 27 '17 at 17:11
  • @MehmetKaplan Hard to say without seeing `g_GlobalData`. For instance, if `g_GlobalData.js` starts with `export const data = {...}`, `g_GlobalData.data` should be good, or if it's `const data = {...}; export default data;` then `g_GlobalData` refers to `data`. Make sense? What you export, and how, from `g_GlobalData` is key. – Ted Nov 27 '17 at 17:23
  • 1
    @Ted, makes a perfect sense, even it solved my problem pal. Thank you. For the brief, my export was ```module.exports = {g_GlobalData: g_GlobalData};``` Your comment made me understand actually I should have used ```module.exports = g_GlobalData;``` which I did and solved my problem. :-) Cheers! – Mehmet Kaplan Nov 27 '17 at 17:39
  • @MehmetKaplan excellent! Glad you got it working. – Ted Nov 27 '17 at 20:06

0 Answers0