title: How to use preload.js properly in Electron
body: <p>I'm trying to use Node modules (in this example, <code>fs</code>) in my <code>renderer</code> processes, like this:</p>
  
  <pre><code>// main_window.js
  const fs = require('fs')
  
  function action() {
      console.log(fs)
  }
  </code></pre>
  
  <p><sup>Note: The <code>action</code> function gets called when I press a button in my <code>main_window</code>.</sup></p>
  
  <p>But this gives an error:</p>
  
  <pre><code>Uncaught ReferenceError: require is not defined
      at main_window.js:1
  </code></pre>
  
  <p>I can solve this issue, <a href="https://stackoverflow.com/a/55908510/6282576">as suggested by this accepted answer</a>, by adding these lines to my <code>main.js</code> when initializing the <code>main_window</code>:</p>
  
  <pre><code>// main.js
  main_window = new BrowserWindow({
      width: 650,
      height: 550,
      webPreferences: {
          nodeIntegration: true
      }
  })
  </code></pre>
  
  <p>But, <a href="https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content" rel="noreferrer">according to the docs</a>, this isn't the best thing to do, and I should instead, create a <code>preload.js</code> file and load these Node modules there and then use it in all of my <code>renderer</code> processes. Like this:</p>
  
  <p><code>main.js</code>:</p>
  
  <pre><code>main_window = new BrowserWindow({
      width: 650,
      height: 550,
      webPreferences: {
          preload: path.join(app.getAppPath(), 'preload.js')
      }
  })
  </code></pre>
  
  <p><code>preload.js</code>:</p>
  
  <pre><code>const fs = require('fs')
  
  window.test = function() {
      console.log(fs)
  }
  </code></pre>
  
  <p><code>main_window.js</code>:</p>
  
  <pre><code>function action() {
      window.test()
  }
  </code></pre>
  
  <p>And it works!</p>
  
  <hr>
  
  <p>Now my question is, isn't it counter-intuitive that I should write most of the code of my <code>renderer</code> processes in <code>preload.js</code> (Because only in <code>preload.js</code> I have access to Node modules) and then merely call the functions in each <code>renderer.js</code> file (for example here, <code>main_window.js</code>)? What am I not understanding here? </p>