Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question What is the best way to include a node module into Unity WebGL?

Discussion in 'Web' started by tinahoeflich, May 19, 2023.

  1. tinahoeflich


    May 19, 2023
    I have to include a node module into my Unity WebGL Project.
    is not possible in .jslib files, (it will throw a
    ReferenceError: require is not defined
    ) what is the best way to stil include a node module?

    I have been researching for days now and can't seem to find a proper way to do it, so I would really appreciate if someone can help me on this.
  2. CodeSmile


    Apr 10, 2014
    Perhaps this video helps?

    I have no exp with NodeJs but since NodeJS is a server technology you cannot embed it into your Unity app or its JS wrapper. Unity WebGL runs in the browser, it's basically a client/remote service/program that somehow needs to communicate with the NodeJS server interface.

    I would first try to approach it the common way web services "talk" to each other, via POST/GET using Unity's WebRequest API.

    You can also make calls to Javascript using the C# interface. Here's more info but it may be outdated. Calling your own javascript from C# means you can then route calls to the NodeJS lib and back to Unity, but I would advise that only if you are more comfortable within the JS world or if it's technically required to have that JS interface for some reason.
    Last edited: May 19, 2023
  3. TolikP


    Dec 6, 2022
    Did you find any solution for this?
  4. jukka_j


    Unity Technologies

    May 4, 2018
    require() is a function that exists in Node.js:

    Browsers do not have require(), so it is not possible to run any code that uses it in a browser as-is. This limitation does not have to do with .jslib files, which are Emscripten JS library files.

    Alternative module import mechanisms to Node.jses require() are ES6 Modules, or different web frameworks. These are discussed e.g. in this StackOverflow thread.

    These would be something that the Node.js package author would need to have thought about while developing their package. I.e. they would have made their package dual-usable in Node.js via require() and then maybe as ES modules using the browser-provided ES import syntax.