简体   繁体   中英

Why can't I use functions from javascript-files that are imported by require()?

I started using electron .

In the index.html of electron-quick-start a JavaScript file is included using require() .

<script>
  // You can also require other files to run in this process
  require('./renderer.js')
</script>

Now I defined a simple function named flash() in renderer.js , as well as a log output:

function flash(text) {
  alert("Text: " + text + "!");
}

console.log("Renderer loaded.");

After starting the electron app, I the the log-output in the console of the dev-tools. but calling flash() does not work.

When including the script using

<script src='./renderer.js'></script>

I can call the function.

  • Where does the require() function come from?
  • Why can't I use the function when including the file using require ?
  • How can I use function defined in files that are required?
  • When should I use require() and when should I use src="" ?

Where does the require() function come from?

The require in Electron is pretty much similar to require in Node.js. Electron is not just a web browser; it is intended for you to build desktop applications using HTML, CSS, and JavaScript. Because it is intended for more than the web, I assume that the creators of Electron added their own little touch to make it an even more awesome piece of technology that you can use. You can read more about it here: https://nodejs.org/api/modules.html#modules_modules .

Why can't I use the function when including the file using require?

It's because they are enclosed inside the module, and hence why it isn't available to any other script files.

How can I use function defined in files that are required?

In order to use the flash function, you would need to export it, like so:

function flash(text) {
  alert("Text: " + text + "!");
}
module.exports.flash = flash;
// Note: this is how we export. We assign properties to the `module.exports`
//   property, or reassign `module.exports` it to something totally
//   different. In  the end of the day, calls to `require` returns exactly
//   what `module.exports` is set to.

console.log("Renderer loaded.");

But that alone won't let you readily use the flash function; you will have to explicitly grab it from the require call like so:

<script>
  // You can also require other files to run in this process
  var renderer = require('./renderer.js');

  renderer.flash('Some text');
</script>

When should I use require() and when should I use src=""?

Disclaimer: my opinion.

Prefer to use require always. Only use script src='' when you want to import libraries that don't use require but instead opt to declare variables globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM