原因使用js组件进行反应

问题描述 投票:0回答:2

我遇到了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

javascript ffi reason bucklescript reason-react
2个回答
2
投票

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

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

documentation on the package-specs configuration item


1
投票

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

// 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
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.