I am writing an application with the Node.js, Express.js, and Jade combination.
I have file client.js
, which is loaded on the client. In that file I have code that calls functions from other JavaScript files. My attempt was to use
var m = require('./messages');
in order to load the contents of messages.js
(just like I do on the server side) and later on call functions from that file. However, require
is not defined on the client side, and it throws an error of the form Uncaught ReferenceError: require is not defined
.
These other JavaScript files are also loaded at runtime at the client, because I place the links at the header of the webpage. So the client knows all the functions that are exported from these other files.
How do I call these functions from these other JavaScript files (such as messages.js
) in the main client.js
file that opens the socket to the server?
You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).
1) require()require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.
To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.
This is because require()
does not exist in the browser/client-side JavaScript.
Now you're going to have to make some choices about your client-side JavaScript script management.
You have three options:
<script>
tag.CommonJS client side-implementations include (most of them require a build step before you deploy):
You can read more about my comparison of Browserify vs (deprecated) Component.
AMD implementations include:
Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With