533

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
  • 6
    Why don't you just <script src="messages.js"></script> and call them after that? 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? 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
    – Hephaestus
    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......... 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?
    – ggorlen
    Sep 21, 2022 at 15:17

11 Answers 11

590

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.

14
  • 7
    I think JSPM should be added to the list.
    – Martijn
    Feb 11, 2016 at 9:12
  • 93
    Could I get an example of using the <script> tag to import a React class without the use of a nodeJs package manager? May 12, 2016 at 16:50
  • 5
    Anybody know how to use require on the client side with webpack? Still getting "require is not defined error" May 30, 2016 at 21:31
  • 5
    Yeah. Component is now deprecated github.com/componentjs/component
    – i_emmanuel
    Jul 17, 2017 at 12:35
  • 11
    how can I do it using <script> tag?
    – FLAK-ZOSO
    Oct 10, 2021 at 7:20
89

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.

6
  • 2
    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. Mar 23, 2021 at 23:46
  • 1
    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. Mar 25, 2021 at 6:22
  • 1
    This won't work if you don't use Electron. If you don't use Electron, the above code will fail with "Unexpected token '}'". May 5, 2021 at 5:23
  • 2
    This is not considered safe and is a discouraged practice now. Nov 11, 2021 at 7:15
  • @Kibonge Murphy Does this mean that all Node modules that would actually be useful in Electron are off limits? Such as fs?
    – HeadCode
    Jan 26, 2022 at 1:21
64

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
34

Replace all require statements with import statements. Example:

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

// After:
import Web3 from 'web3';

It worked for me.

3
  • For reference, it might be helpful to go through this question regarding the difference between the two. Aug 1, 2020 at 0:26
  • 3
    You might need to use type=module, which requires you to export the functions and variable names for them to work. May 5, 2021 at 5:24
  • 1
    Those requires are generated automatically from TypeScript. How to avoid that? Dec 16, 2022 at 19:32
4

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
4

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
  • 11
    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.
    – ggdx
    Oct 26, 2019 at 15:17
  • 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?
    – AntoCode
    Mar 25, 2021 at 12:14
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();
3
window = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
    }
});
3
  • 2
    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. Mar 29, 2021 at 12:57
  • 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?
    – markp-fuso
    Mar 29, 2021 at 13:11
  • 1
    although it is not clear but somehow is worked. May 19, 2021 at 14:50
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
1

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.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.