带有 React 的可嵌入 JavaScript 小部件

2022-01-18 00:00:00 reactjs widget javascript

是否可以使用 React JavaScript 库创建可嵌入的 JavaScript 小部件,其中:

Is it possible to create an embeddable JavaScript widget using the React JavaScript library, where:

  1. React 库嵌入"在小部件中
  2. 嵌入的 React 库的版本可以与加载小部件的页面上的 React 库不同,就像可以使用 jQuery 一样.

我正在寻找如下所述的功能:

I'm lookin for functionality as described in:

  • http://blog.swirrl.com/articles/creating-asynchronous-embeddable-javascript-widgets/
  • http://shootitlive.com/2012/07/developing-an-embeddable-javascript-widget/

推荐答案

对于你提到的需求,最好的解决方案是browserify(或类似的).使用 reactify 转换,您可以让 JSX 到 JS 一步完成.Browserify(和 Webpack)在 React 社区中非常常见,因此几乎所有库都发布到 npm 以方便使用.

For the requirements you mentioned, the best solution is browserify (or similar). Using reactify transform you can have the JSX to JS happen all in one step. Browserify (and Webpack) are very common the react community, so nearly all libraries are published to npm for easy consumption.

Browserify 将您的 JavaScript、您选择的 React 版本和任何库打包到一个 JS 文件中,该文件不使用全局变量或与页面上运行的其他代码冲突的其他模式.

Browserify packs your JavaScript, your React version of choice, and any libraries into a single JS file which doesn't use globals or other patterns that conflict with other code running on the page.

您还可以查看诸如 react-css 之类的一些库,以将您的样式与页面样式隔离开来.样式也将在您的包中隔离.当然,如果页面执行 div {margin: 1em} 之类的操作,则唯一的解决方案是 iframe 或 web-components.

You can also look into some libs like react-css to isolate your styles from the page styles. The styles will also be isolated in your bundle. Of course if the page does something like div {margin: 1em}, the only solutions are iframes or web-components.

相关文章