Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack, babel: es6 import vs. require for Fabric.js

I am using webpack and babel in my development tool chain; when running the following code:

import * as fabric from 'fabric';

var canvas = new fabric.Canvas('canvas');

I get the following error:

_fabric2.default.Canvas is not a constructor

Whereas the same code works fine if I use require('fabric'); instead of import.

I tried different ways of calling import but none of them worked.

My linting tool complains of the undefined fabric variable, so I would like to have it properly defined. Surprisingly (for me), this code doesn't work neither:

var fabric = require("fabric");

I get the following error in this case:

fabric.Canvas is not a constructor

What am I doing wrong ?

like image 227
mguijarr Avatar asked May 02 '16 14:05

mguijarr


2 Answers

In my current setup using fabric from NPM, I use

import {fabric} from 'fabric'

to access to fabric global object.

like image 146
kcjpop Avatar answered Oct 30 '22 09:10

kcjpop


Looking into the source code you can figure out that fabric is made global by settin it on the window object. So once you require or import you can start using fabric directly. If you want it to be well defined you can get the definition from the window object. var fabric = window['fabric']

https://github.com/kangax/fabric.js/blob/master/dist/fabric.js

like image 27
raiyan Avatar answered Oct 30 '22 09:10

raiyan