Rails 5/6: How to include JS functions with webpacker?

后端 未结 4 811
栀梦
栀梦 2020-12-05 19:50

I am trying to update a Rails 3 app to Rails 6 and I have problems with the now default webpacker since my Javascript functions are not accessible.

I get: Refe

4条回答
  •  时光取名叫无心
    2020-12-05 20:20

    Looking at how webpacker "packs" js files and functions:

    /***/ "./app/javascript/dashboard/project.js":
    /*! no static exports found */
    /***/ (function(module, exports) {
    
      function myFunction() {...}
    

    So webpacker stores these functions within another function, making them inaccessible. Not sure why that is, or how to work around it properly.

    There IS a workaround, though. You can:

    1) change the function signatures from:

    function myFunction() { ... }
    

    to:

    window.myFunction = function() { ... }
    

    2) keep the function signatures as is, but you would still need to add a reference to them as shown here: window.myFunction = myFunction

    This will make your functions globally accessible from the "window" object.

提交回复
热议问题