Search code examples
scala.jsscalajs-bundler

TypeError: Cannot read property 'freeze' of undefined


I am trying to create a facade for the npm library avsc. When I compile with sbt fastOptJS::webpack and open the .html file, I get Uncaught TypeError: Cannot read property 'freeze' of undefined from the file treepad-fastopt-bundle.js in the line $g["Object"]["freeze"]($env);. I don't use Object.freeze it anywhere.

This is the facade code:

import buffer.Buffer
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSImport, JSName}

@js.native
trait Type extends js.Object {
  @JSName("val")
  def toBuffer(v: String): Buffer = js.native
}

@JSImport("avsc/", "avro")
@js.native
object avro extends avro

@js.native
trait avro extends js.Object {
  def parse(schema: js.Any): Type = js.native
}

Also have a look at the whole project, it's very little code.

Using @JSImport("avsc", JSImport.Namespace) instead did not change anything.


Solution

  • The problem comes from the fact that, in your webpack configuration file, you tell webpack to target the Node.js execution environment instead of web browsers.

    However, as you noticed, the avsc module uses the fs Node.js module, which is not available in web browsers. It seems that the right workaround, in this case, is to add the following line to your webpack configuration file:

    module.exports.node = { fs: "empty" };
    

    Last but not least, the right @JSImport is indeed @JSImport("avsc", JSImport.Namespace) because you want to import the whole avsc module, as shown in the documentation.