title: Rails 6 Webpacker calling javascript function from Rails view
body: <p>I have following structure for Javascript in my Rails 6 app using Webpacker.</p>
  
  <pre><code>app/javascript
    + packs
      - application.js
    + custom
      - hello.js
  </code></pre>
  
  <p>Below shown is the content in the above mentioned JS files</p>
  
  <p><strong>app/javascript/custom/hello.js</strong></p>
  
  <pre><code>  export function greet(name) {
      console.log("Hello, " + name);
    }
  </code></pre>
  
  <p><strong>app/javascript/packs/application.js</strong></p>
  
  <pre><code>  require("@rails/ujs").start()
    require("jquery")
    require("bootstrap")
  
    import greet from '../custom/hello'
  </code></pre>
  
  <p><strong>config/webpack/environment.js</strong></p>
  
  <pre><code>const { environment } = require('@rails/webpacker')
  
  const webpack = require('webpack')
  environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      Popper: ['popper.js', 'default']
    })
  )
  
  module.exports = environment
  </code></pre>
  
  <p>Now in my Rails view I am trying to use the imported function <code>greet</code> like shown below</p>
  
  <p><strong>app/views/welcome/index.html.haml</strong></p>
  
  <pre><code>  - name = 'Jignesh'
  
    :javascript
  
      var name = "#{name}"
      greet(name)
  </code></pre>
  
  <p>When I load the view I am seeing <code>ReferenceError: greet is not defined</code> error in browser's console.</p>
  
  <p>I tried to search for a solution to this problem and found many resources on web but none turned out to help me. At last when I was drafting this question in the suggestions I found <a href="https://stackoverflow.com/questions/59349091/how-to-execute-custom-javascript-functions-in-rails-6">How to execute custom javascript functions in Rails 6</a> which indeed is close to my need <strong>however the solution shows a workaround but I am looking for a proper solution</strong> for the need because I have many views which needs to pass data from Rails view to JS functions to be moved custom files under <code>app/javascript/custom</code> folder.</p>
  
  <p>Also I would highly appreciate if anybody can help me understand the cause behind the <code>ReferenceError</code> I am encountering.</p>
  
  <p><strong>Note</strong>: </p>
  
  <p>I am not well-versed in Javascript development in Node realm and also new to Webpacker, Webpack, Javascript's modules, <code>import</code>, <code>export</code>, <code>require</code> syntax etc so please bear with me if you find anything silly in what I am asking. I have landed up in above situation while trying to upgrade an existing Rails app to use version 6.</p>