【问题标题】:Reason React using js component原因 React 使用 js 组件
【发布时间】:2019-04-14 23:09:08
【问题描述】:

我在使用 js 互操作时遇到问题。我正在尝试像这样使用 js 组件react-slick

// src/interop/Carousel.js
import React from 'react'
import Slider from 'react-slick'

export function Carousel(props) {
  return (
    <Slider>
      <div>
        <h3>{props.name} 1</h3>
      </div>
    </Slider>
  )
}


/* src/Carousel.re */
[@bs.module  "./interop/Carousel"] [@react.component]
external  make: (~name: string) =>  React.element  =  "";

/* src/index.re */
ReactDOMRe.renderToElementWithId(<Carousel  name="ahaha"  />,  "carousel");

但是在 webpack 中遇到了这个错误:

ERROR in ./lib/js/src/Index.bs.js
Module not found: Error: Can't resolve './interop/Carousel' in '[...]/reason_react_example/lib/js/src'
 @ ./lib/js/src/Index.bs.js 6:15-44

所以看起来BS在编译时没有考虑Carousel.js文件?

顺便说一句,我正在关注这个reason-react doc

【问题讨论】:

  • 这个文件存在吗? lib/js/src/interop/Carousel.js?
  • 它不存在
  • 嗯 - 这不是这里的问题吗?
  • hmm,看来我得把文件直接放到lib/js/src 并设置webpack 来加载jsx

标签: javascript ffi reason bucklescript reason-react


【解决方案1】:

默认情况下,BuckleScript 会将生成的 js 工件放在 lib/js/... 中,因此您必须编写与此相关的导入,或者配置 bsb 以将工件放在源文件旁边。您可以通过在bsconfig.json 中为给定的package-spec 设置"in-source": true 来完成后者。例如:

{
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  }
}

请参阅documentation on the package-specs configuration item

【讨论】:

    【解决方案2】:

    经过一些调整,这对我有用:

    // lib/js/src/interop/Carousel.js
    import React from 'react'
    import Slider from 'react-slick'
    
    const Carousel = props => {
      return (
        <Slider>
          <div>
            <h3>{props.name} 1</h3>
          </div>
        </Slider>
      )
    }
    
    export default Carousel
    
    
    // src/Carousel.re    
    [@bs.module "./interop/Carousel"] [@react.component]
    external make: (~name: string) => React.element = "default"; // handle default export
    
    // src/Index.re
    ReactDOMRe.renderToElementWithId(<Carousel name="it works!" />, "carousel");
    

    由于Carousel.js 使用的是 es6 和 jsx,我需要设置 webpack 来使用它(es6jsx)。而bsconfig.json 需要有这些设置:

    "reason": {
      "react-jsx": 3
    },
    "package-specs": [
      {
        "module": "commonjs",
        "in-source": false
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2012-02-18
      • 2018-04-12
      • 2017-03-25
      • 2015-12-13
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多