首页 > 解决方案 > ES6 导入中断 Gatsby 构建:WebpackError:ReferenceError:未定义元素

问题描述

我想在我的组件中包含以下 npm 包:tiny-slider-react。

但是,虽然它在 Gatsby Develop 中运行良好,但 Gatsby Build 失败并显示以下消息:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  3 |   "use strict";
  4 | 
> 5 |   if(!("remove" in Element.prototype)){
    | ^
  6 |     Element.prototype.remove = function(){
  7 |       if(this.parentNode) {
  8 |         this.parentNode.removeChild(this);


  WebpackError: ReferenceError: Element is not defined

  - childNode.remove.js:5 
    [lib]/[ventura-slider]/src/helpers/childNode.remove.js:5:1

  - childNode.remove.js:12 Object../node_modules/ventura-slider/src/helpers/childNode.remove.js
    [lib]/[ventura-slider]/src/helpers/childNode.remove.js:12:2

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - tiny-slider.module.js:1 Module../node_modules/ventura-slider/src/tiny-slider.module.js
    [lib]/[ventura-slider]/src/tiny-slider.module.js:1:1

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - Carousel.js:19 Object../node_modules/tiny-slider-react/build/Carousel.js
    [lib]/[tiny-slider-react]/build/Carousel.js:19:19

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - index.js:7 Object../node_modules/tiny-slider-react/build/index.js
    [lib]/[tiny-slider-react]/build/index.js:7:17

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1


  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1


  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - sync-requires.js:12 Object../.cache/sync-requires.js
    lib/.cache/sync-requires.js:12:57

  - bootstrap:19 __webpack_require__
    lib/webpack/bootstrap:19:1

  - static-entry.js:9 Module../.cache/static-entry.js
    lib/.cache/static-entry.js:9:22

注释掉这个导入和它的 React 组件解决了这个问题。

Slideview.js

import React from 'react';
import TinySlider from "tiny-slider-react";

...

class SlideView extends React.Component{
    render(){
        return(
            <TinySlider settings={settings}>
                ...
            </TinySlider>
        );
    }
}

预期:滑块在生产中的工作方式与开发类似。实际结果:构建中断

标签: javascriptreactjsgatsby

解决方案


原来我必须有以下几行到 gatsby-node.js

盖茨比-node.js

// /**
//  * Implement Gatsby's Node APIs in this file.
//  *
//  * See: https://www.gatsbyjs.org/docs/node-apis/
//  */

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
    if (stage === "build-html") {
      actions.setWebpackConfig({
        module: {
          rules: [
            {
              test: /tiny-slider-react/,
              use: loaders.null(),
            },
          ],
        },
      })
    }
  }

它位于此文档页面的底部。 https://www.gatsbyjs.org/docs/debugging-html-builds/

感谢菲利普的帮助


推荐阅读