Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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? – MightyMouse Sep 27, 2013 at 20:45 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 @Sterling Archer... If there are 100 such files... we can't keep on loading the, in HTML right......... – Baradwaj Aryasomayajula 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--on LLM strike Sep 21, 2022 at 15:17

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:

  • Use the <script> tag.
  • Use a CommonJS implementation. It has synchronous dependencies like Node.js
  • Use an asynchronous module definition (AMD) implementation.
  • CommonJS client side-implementations include (most of them require a build step before you deploy):

  • Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  • 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.
  • 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:

  • 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.

    Could I get an example of using the <script> tag to import a React class without the use of a nodeJs package manager? – Louie Bertoncin May 12, 2016 at 16:50 Anybody know how to use require on the client side with webpack? Still getting "require is not defined error" – user3226932 May 30, 2016 at 21:31

    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.

    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. – Mike Baxter Mar 23, 2021 at 23:46 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. – Kibonge Murphy Mar 25, 2021 at 6:22 This won't work if you don't use Electron. If you don't use Electron, the above code will fail with "Unexpected token '}'". – Someone_who_opposes_SE May 5, 2021 at 5:23 @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

    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.

    @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 – Kamil Kiełczewski Aug 7, 2018 at 14:20

    Replace all require statements with import statements. Example:

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

    It worked for me.

    For reference, it might be helpful to go through this question regarding the difference between the two. – tripathiakshit Aug 1, 2020 at 0:26 You might need to use type=module, which requires you to export the functions and variable names for them to work. – Someone_who_opposes_SE May 5, 2021 at 5:24

    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();
    
  • Get the latest release from the RequireJS download page
    It is the file for RequestJS which is what we will use.
  • 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')

    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

    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();
                    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.
    – Alexander Leithner
                    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
    

    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.

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.