Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fabric js as ES6 import in Chrome doesn't work

On my website I don't want to bundle but instead use ES6 modules directly (works for the audience)

I try importing fabric.js by

import {fabric} from "../node_modules/fabric/dist/fabric.js"; like I do when I bundle (for bundles it works fine).

however when starting the website I get

"Uncaught SyntaxError: The requested module '../node_modules/fabric/dist/fabric.js' does not provide an export named 'fabric'"

if I change the above to import * as FAB from "../node_modules/fabric/dist/fabric.js"; I get

Uncaught TypeError: Cannot read property 'fabric' of undefined at fabric.js:3224

Any ideas on how to use fabric directly as ES6 module without bundling? Needless to say I do not have this issue with other modules I import when using Chrome 76.0.3809.132

Upgraded to fabric 3.4 with no avail. Let me paste my entire code here: The html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <script type="module" src="./start.js"></script>
   </head>

   <body>

   </body>
</html>

and the JS from which I removed everything else

import fabric from '../node_modules/fabric/dist/fabric.min.js';

Still same Error

Uncaught SyntaxError: The requested module '../node_modules/fabric/dist/fabric.min.js' does not provide an export named 'default'

like image 340
TomFree Avatar asked Aug 29 '19 17:08

TomFree


2 Answers

The way fabric.js is written, it won't work with ES6 Module import. This is because fabric relies on this being a reference to window in browser environments, e.g. when it uses IIFEs to add properties to the fabric object like this:

(function(global) {

  var fabric  = global.fabric || (global.fabric = { }),

  // ...
  fabric.something = somethingElse
})(typeof exports !== 'undefined' ? exports : this);

Normally, this would be passed as a reference to window, but not when the script is loaded as a Module (MDN mentions it here among other places).

That's why even if you correctly import it via

import fabric from '../node_modules/fabric/dist/fabric.js'

You'll get errors like

Uncaught TypeError: Cannot read property 'fabric' of undefined

Unless you want to get your hands dirty and patch the library source, you'd probably be better off loading fabric in a separate, non-module script tag.

like image 63
shkaper Avatar answered Nov 15 '22 13:11

shkaper


Please try to import it like the below,

import fabric from '../node_modules/fabric/dist/fabric.min.js'


class App extends Component {

  render() {
    console.log(fabric) // you can get fabric object
    return (
      <div class="blahblah"> 
      </div>
    )

  }
}
like image 1
Kannan G Avatar answered Nov 15 '22 11:11

Kannan G