sa125
sa125

Reputation: 28971

Using custom fabric.js classes in node.js

I'm using a couple of custom fabric.js classes in my app to render and encapsulate some additional data attributes as suggested here.

Now that I have the JSON data generated by these, I'd like to render the canvas and write it to PNG image on the server using node.js and fabric's npm package. This works well with the built in fabric classes like fabric.Rect or fabric.Text, but my customizations keep throwing strange require errors.

Basically, the custom file looks like this:

fabric.custom.js

// without this node raises "fabric is not defined" error
var fabric = fabric || {};

if (typeof exports !== 'undefined') {
  exports.fabric = fabric;
}

// actual implementations
fabric.NamedImage = fabric.util.createClass(fabric.Image, {

  type: 'named-image',

  // custom overrides
  // ...
});

And are loaded into my node script like so:

var fabric = require('fabric').fabric;
require('./fabric.custom');

// read JSON and write to PNG ..

When I run it, the following exception occurs:

/Users/sa125/code/nodetest/fabric.custom.js:13
fabric.NamedImage = fabric.util.createClass(fabric.Image, {
                               ^
TypeError: Cannot call method 'createClass' of undefined
    at Object.<anonymous> (/Users/sa125/code/nodetest/fabric.custom.js:13:32)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/sa125/code/nodetest/test.js:4:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

Is there anything special I need to do to re-use my client side fabric.js code with node.js?

Upvotes: 0

Views: 1361

Answers (1)

DF_
DF_

Reputation: 3973

This is simply because node.js has no global scope. What happens in the browser is that the original fabric variable gets assigned in the DOM under the global namespace. This means that in your custom module, the fabric variable already exists.

In node.js that variable does not exist as each file has its own local scope. When node.js looks for the fabric variable in the custom file, it therefore cannot find it as it hasn't been created yet. What you need to do is extend the original object of fabric after the first require with your additional methods, or create a new variable on the require and merge the two objects together. Either way, require('...'); is useless in node.js without an assignment to a variable.

Upvotes: 1

Related Questions