I'm currently experimenting with integrating fabric.js into a Laravel 5.4 application using Typescript and Webpack, alongside other modules that are functioning properly in the browser. Although @types/fabric is installed and Typescript is behaving correctly, I have encountered some challenges due to my lack of experience with Typescript and Webpack.
The Issue
result.js:198 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_1_fabric___default.a.Canvas is not a constructor
Approach A
code.ts
import fabric from "fabric";
const canvas = new fabric.Canvas('my-canvas');
result.js
var canvas = new __WEBPACK_IMPORTED_MODULE_1_fabric__default.a.Canvas('my-canvas');
The usage of WEBPACK_IMPORTED_MODULE_1_fabric__default refers to an object where 'fabric' serves as the key.
const canvas = new fabric.fabric.Canvas('my-canvas');
This configuration would function within Webpack, yet it does not adhere to type inspections.
Approach B
code.ts
import * as fabric from "fabric";
const canvas = new fabric.Canvas('my-canvas');
result.js
var canvas = new __WEBPACK_IMPORTED_MODULE_1_fabric__["Canvas"]('my-canvas');
In this case, WEBPACK_IMPORTED_MODULE_1_fabric contains an object where 'fabric' is the key, mirroring the situation in Approach A.
Approach C
code.ts
import {Canvas} from "fabric";
const canvas = new Canvas('my-canvas');
result.js
var canvas = new __WEBPACK_IMPORTED_MODULE_1_fabric__["Canvas"]('my-canvas');
Ultimately, this approach aligns closely with Approach B.
excerpt of webpack.mix.js
.webpackConfig({
module: {
rules: [
// Webpack configuration rules here...
]
},
plugins: [
// Plugin configurations here...
],
resolve: {
// Resolve configurations here...
}
It appears that the issue lies within Webpack or perhaps the babel-loader not recognizing the fabric namespace appropriately.
Hence, the main question at hand pertains to whether there exists a method to instruct Webpack on how to handle this import in a manner that directly references fabric (or a similar imported library) or if there's a way to import it into Typescript in a manner that satisfies Webpack as well?