Chrome 中作为 ES6 导入的 fabric js 不起作用

fabric js as ES6 import in Chrome doesn't work

在我的网站上,我不想捆绑而是直接使用 ES6 模块(适用于观众)

我尝试通过

导入fabric.js

import {fabric} from "../node_modules/fabric/dist/fabric.js"; 就像我捆绑时所做的那样(对于捆绑它工作正常)。

但是在启动网站时我得到

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

如果我把上面的改成 import * as FAB from "../node_modules/fabric/dist/fabric.js"; 我得到

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

关于如何在不捆绑的情况下直接使用 fabric 作为 ES6 模块有什么想法吗? 不用说,我在使用 Chrome 76.0.3809.132

时导入的其他模块没有这个问题

升级到 fabric 3.4 无果。让我在这里粘贴我的整个代码: html

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

   <body>

   </body>
</html>

以及我从中删除所有其他内容的 JS

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

还是一样的错误

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

请尝试像下面这样导入它,

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

  }
}

fabric.js的写法,ES6 Module import 无效。这是因为 fabric 依赖于 this 作为浏览器环境中对 window 的引用,例如当它使用 IIFE 向 fabric 对象添加属性时,如下所示:

(function(global) {

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

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

通常,this 将作为对 window 的引用传递,但当脚本作为模块加载时(MDN mentions it here 以及其他地方)则不会。

这就是为什么即使您通过

正确导入它
import fabric from '../node_modules/fabric/dist/fabric.js'

你会得到类似

的错误
Uncaught TypeError: Cannot read property 'fabric' of undefined

除非您想亲自动手修补库源代码,否则最好在单独的非模块脚本标记中加载 fabric。

以这种方式导入对我有用

 import { fabric } from "fabric"