Client on Node.js: Uncaught ReferenceError: require is not defined
#1
The issue you are running into is because `require` is specific to Node.js which implements the CommonJS module system. Client-side JavaScript typically doesn't recognize `require` unless you're using a module bundler like Webpack or Browserify. If you want to use modules on the client side without these tools, you might consider using ES6 modules, which are supported by most modern browsers.
Here's how you can use ES6 modules in your client-side code:
First, make sure to declare your JavaScript file as a module by using the `type="module"` attribute in your script tag. For example:

Code:
<
    script type = "module"
src = "client.js" > < /script>

In your `messages.js`, you would export the functions you want to use elsewhere:

Code:
// messages.js
export function showMessage(msg) {
    console.log(msg);
}
// Export other functions as needed

Then, in your `client.js`, you can import these functions:

Code:
// client.js
import * as m from './messages.js';
m.showMessage('This is a message from the messages module.');

This should solve the `require` issue on the client side.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)