SyntaxError: export declarations may only appear at top level of a module when trying to import office-ui-fabric in a Gatsbyjs blog

SyntaxError: export declarations may only appear at top level of a module when trying to import office-ui-fabric in a Gatsbyjs blog

我正在尝试使用 gatsby js 在博客 build 中添加 OfficeUI 结构组件。

我一导入任何组件,网站就停止工作。

使用 develop 命令,我可以在浏览器控制台中看到:SyntaxError: export declarations may only appear at top level of a module

如何解决这个问题? (我是节点开发的新手)。

我所做的搜索表明 babel 不使用 es2015 预设存在问题。但是,我仔细检查了一下,.babelrc 文件提到了这个预设。

这是我完成的完整操作(如果重要,在 Windows 10 x64 上):

  1. 克隆了 gatsby-starter-blog-no-styles 仓库:

    gatsby.cmd new someblog https://github.com/noahg/gatsby-starter-blog-no-styles
    cd someblog
    npm install
    

    喝杯咖啡(很快就会转到yarn)

  2. 检查是否有效

    gatsby develop
    

    打开浏览器 (http://localhost:8000)。还行

  3. 添加了 office ui fabric react 组件

    npm install --save office-ui-fabric-react
    

    重新启动 gatsby 开发。还在工作

  4. 修改src/layouts/index.js文件导入office组件

    import React from 'react'
    import Link from 'gatsby-link'
    import { Button } from 'office-ui-fabric-react/lib/Button'
    
    class Template extends React.Component {
      ....
    

    瞧!它停止工作。在浏览器控制台中,我看到一个错误:SyntaxError: export declarations may only appear at top level of a module

我在 GH 中放入了一个完整的复制库:https://github.com/stevebeauge/repro-gatsbyjs-officeui-error

[编辑] 挖掘了一下,我可以在生成的 'common.js' 文件中看到错误:

/***/ "./node_modules/office-ui-fabric-react/lib/Button.js":
/***/ (function(module, exports) {

    export * from './components/Button/index';
    //# sourceMappingURL=Button.js.map

/***/ }),

这里的export好像是禁止的,导致babel的问题(虽然没找到解决办法)

最近我偶然发现了类似的错误,我的解决方案是 明确地lib-commonjs 导入:

import { Button } from 'office-ui-fabric-react/lib-commonjs/Button'; 

而不是

import { Button } from 'office-ui-fabric-react/lib/Button'

似乎是因为 babel 没有将 office-ui-fabric-react 转换为 CommonJS 模块而发生错误。