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

走远了吗. 提交于 2019-12-21 07:22:12

问题


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
});           


来源:https://stackoverflow.com/questions/36984795/webpack-babel-es6-import-vs-require-for-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!