573

I have a file client.js, which is loaded on the client side. 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?

5
  • 7
    Why don't you just <script src="messages.js"></script> and call them after that? Commented Sep 27, 2013 at 20:34
  • 3
    Perhaps this can be a solution, but there is another thing that concerns me. I also have a file called "representation.js" for abstracting the representation that is common to the client and the server. In that file I also have require statements and on the server side it should be ok because I am running node. However, on the client side this will be an issue. What do you think? Commented Sep 27, 2013 at 20:45
  • 4
    For newbies like me (who couldn't even spell "npm" a week ago! :-), it may be helpful to understand that browserify's --require option causes require() to be defined on the client side. See: lincolnloop.com/blog/speedy-browserifying-multiple-bundles Commented Mar 12, 2016 at 18:34
  • 4
    @Sterling Archer... If there are 100 such files... we can't keep on loading the, in HTML right......... Commented Jun 9, 2016 at 18:58
  • "client on node.js" is a confusing title because "client" usually refers to the web browser client, while node.js is a server-side environment. Can we clarify whether this is browser or Node? Commented Sep 21, 2022 at 15:17

12 Answers 12

618

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:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  2. Webpack - Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
  3. Rollup - a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs (deprecated) Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.

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.

Sign up to request clarification or add additional context in comments.

14 Comments

I think JSPM should be added to the list.
Could I get an example of using the <script> tag to import a React class without the use of a nodeJs package manager?
Anybody know how to use require on the client side with webpack? Still getting "require is not defined error"
Yeah. Component is now deprecated github.com/componentjs/component
how can I do it using <script> tag?
|
97

I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron') 

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() { // Create a new window addItemWindown = new BrowserWindow({ width: 300, height: 200, title: 'Add Item', // The lines below solved the issue webPreferences: { nodeIntegration: true, contextIsolation: false } })} 

That solved the issue for me. The solution was proposed here.

7 Comments

Is this solution safe? I've heard you shouldn't set nodeIntegration to true - is that right? I am an Electron newbie so this is a genuine question.
Well, it depends on how you are going to use your electron application. The comment thread of the original StackOverflow question I referenced gives a brief overview of the security aspects of doing this. You can follow the thread here. But in short: If this is set to true, your application has access to the node runtime, and if you are executing, potentially malicious, remote code, it's just a recipe for disaster.
This won't work if you don't use Electron. If you don't use Electron, the above code will fail with "Unexpected token '}'".
This is not considered safe and is a discouraged practice now.
@Kibonge Murphy Does this mean that all Node modules that would actually be useful in Electron are off limits? Such as fs?
|
72

ES6: In HTML, include the main JavaScript file using attribute type="module" (browser support):

<script type="module" src="script.js"></script> 

And in the script.js file, include another file like this:

import { hello } from './module.js'; ... // alert(hello()); 

Inside the included file (module.js), you must export the function/class that you will import:

export function hello() { return "Hello World"; } 

A working example is here. More information is here.

3 Comments

@Curse Here stackoverflow.com/a/44591205/860099 is written "Module creates a scope to avoid name collisions." sou you can "manually" put val to window object window.val = val. Here is plunker: Plunker: plnkr.co/edit/aDyjyMxO1PdNaFh7ctBT?p=preview - this solution works
which script.js are you talking about? I couldn't get that.. can you pls tell me
@MrinalAnand its only example name for file with js code
39

Replace all require statements with import statements. Example:

// Before: const Web3 = require('web3'); // After: import Web3 from 'web3'; 

It worked for me.

3 Comments

For reference, it might be helpful to go through this question regarding the difference between the two.
You might need to use type=module, which requires you to export the functions and variable names for them to work.
Those requires are generated automatically from TypeScript. How to avoid that?
5

In my case I used another solution.

As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain

"module": "commonjs" 

But use import and export statements in your referenced files

import { Utils } from "./utils" export interface Actions {} 

Final generated code will always have(at least for TypeScript 3.0) such lines

"use strict"; exports.__esModule = true; var utils_1 = require("./utils"); .... utils_1.Utils.doSomething(); 

2 Comments

Do you really mean ES3? ES3 is 21 years old, from December 1999.
Some old smart TVs hasn't full es5 support. So only es3 works everywhere.
5

This worked for me

  1. Get the latest release from the RequireJS download page
    It is the file for RequestJS which is what we will use.
  2. Load it into your HTML content like this: <script data-main="your-script.js" src="require.js"></script>

Notes!

Use require(['moudle-name']) in your-script.js, not require('moudle-name')

Use const {ipcRenderer} = require(['electron']), not const {ipcRenderer} = require('electron')

2 Comments

Never, ever recommend a "click here", ever. Best case, it's a RickRoll, but we have no idea whatsoever what's awaiting us at the end of that link.
this was help me!! but now my problem is that I need manually change the require... that's a problem, exits somethings in tsconfig that do this when I compile?
3

Even using this won't work. I think the best solution is Browserify:

module.exports = { func1: function () { console.log("I am function 1"); }, func2: function () { console.log("I am function 2"); } }; -getFunc1.js- var common = require('./common'); common.func1(); 

Comments

1

I confirm. We must add:

webPreferences: { nodeIntegration: true } 

For example:

mainWindow = new BrowserWindow({webPreferences: { nodeIntegration: true }}); 

For me, the problem has been resolved with that.

1 Comment

This was basically already answered by stackoverflow.com/a/56342771/2358409
1
window = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); 

3 Comments

Welcome to Stack Overflow and thanks for taking the time to create an answer. However, this very answer has been given numerous times as a solution for this question and thus does not add any value whatsoever. If you could elaborate a bit (by editing this post) on why and how this solution works, this answer could turn to good advice which is exactly what this site is for. Also, this is an answer purely for the Electron framework, which the OP of the question does not even use -- please consider posting (a more elaborate version) on a more appropriate spot.
consider updating with details as to how this answer is different from the other answers; does this answer address an issue not addressed by other answers?
although it is not clear but somehow is worked.
0

People are asking what is the script tag method. Here it is:

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

Or from network:

<script src='https://mycdn.com/myscript.js'></script> 

You need plugin the right url for your script.

Comments

0

I was trying to build metronic using webpack. In my package.json I had to remove the "type": "module" section.

enter image description here

1 Comment

would be nice to add some context. what you are doing is linking the files within your app as commonjs instead of ESM
0

In my case, I gave file name as global.js and it was conflicting with some node.js files, renaming the file fixed for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.