Scala.js runtime error: require is not a function
See original GitHub issueProblem
In Scala.js, Coursier’s NPM dependencies are loaded through js.Dynamic.global.require("...")
. This is problematic for two reasons:
-
Incompatibility with ES modules.
Scala.js projects depending on Coursier should have the choice between generating ES module
import
s or CommonJSrequire
s, but the current implementation of Coursier contains hard-coded calls torequire
. This means that Scala.js projects targeting ES modules will also generaterequire
calls, which won’t work in the browser (unless the bundle is passed through a bundler like Webpack). -
global.require
may beundefined
depending on how the JS code is loaded.For instance, running
console.log(global.require)
printsundefined
in a JS file (loaded usingnode test.js
) but prints therequire
function in a Node.js REPL. See this StackOverflow question.
These two reasons both lead to the same runtime error: TypeError: $g.require is not a function
.
Solution
There are two possible solutions for this:
- Use
@JSImport
overjs.Dynamic.global.require
. - Update to Scala.js 1.x and use
@JSGlobal
to accessrequire
instead ofglobal.require
.
I think solution 1 is probably preferable to solution 2, as Scala.js projects can then target the module system they need. While I think Coursier should eventually move to Scala.js 1.x, solution 2 requires getting all of Coursier’s dependencies to switch to 1.x, which may take time.
Workaround until the solution is implemented
If anyone else needs to work around the issue for now, the hack I’ve found is to use Webpack to bundle my Scala.js output with a JS file containing eval("global.require = require")
. Note that you should then very carefully determine if the Coursier dependencies (xhr2, cheerio, xmldom and sax) should be bundled too (for the Web) or just be available in node_modules
(for Node.js).
Issue Analytics
- State:
- Created 4 years ago
- Comments:11 (11 by maintainers)
Top GitHub Comments
I updated my project to Scala.js 1.1.0 and Coursier v2.0.0-RC6-21, and can confirm that #1715 fixes the problem. I’ll be closing this issue – thank you!
Let’s do this for now then. I don’t really know how many people depend on / use coursier via its Scala.JS artifacts, they’ll find this issue if needed, yes.