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

2020-07-03 07:48发布

问题:

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 ?

回答1:

In my current setup using fabric from NPM, I use

import {fabric} from 'fabric'

to access to fabric global object.



回答2:

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



回答3:

Your import is incorrect. The following works fine:

import 'fabric'

let canvas = new fabric.Canvas('c', {
  backgroundColor: 'rgb(100,100,200)',
  selectionColor: 'blue',
  selectionLineWidth: 2
});