首页 > 解决方案 > 在 html 文件中包含 Reactjs Bundled 组件

问题描述

我有一个reactjs npm 包,我想将它包含在 html 文件中,我在这里得到了捆绑的文件,但我遇到了一个require不是函数的问题,因为我不在 nodejs 项目中。所以我无法导入其他依赖项,有人可以进一步帮助我吗?

console.log(window.React, 'AAB');

window.ReactDOM.render(window.React.createElement(window.ListItem, {
  labelOption: 'name',
  typeOption: 'type',
  valueOption: 'k',
  onRemoveItem: (e) => {console.log('1')},
  item: {name: 'Zeyad', type: 'person'}
}, 'Hi'), document.getElementById("app"));
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link href="https://unpkg.com/react-multiple-selector@1.0.7/dist/styles.css">
  </head>

  <body>
    Name:
    <div id="app"></div>

    <script>
var exports = {};
    </script>
    <script
      crossorigin
src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
    ></script>
    <script src="https://unpkg.com/react-multiple-selector@1.0.7/dist/index.js"></script>
    <script src="https://unpkg.com/react-multiple-selector@1.0.7/dist/ListItem.js"></script>
    <script src="https://unpkg.com/react-multiple-selector@1.0.7/dist/data.js"></script>
  <script src="https://gist.githubusercontent.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js"></script>
  </body>
</html>

标签: javascripthtmlreactjsbabeljs

解决方案


If you want to create a simple reactjs application, you can use umd and an example is available from the react website itself - here

However, not all modules that are built for reactjs support UMD, and you will have to use react in a bundled fashion. Read the official documentation and more. react-multiple-selector looks like it does not support UMD yet.

The inspector console shows that the error is from https://unpkg.com/react-multiple-selector@1.0.7/dist/index.js and https://unpkg.com/react-multiple-selector@1.0.7/dist/ListItem.js

While searching for an option for require in a browser, I came across this SO. However, know that you are trying to hack your way into doing this, and is only a hack not a solution.


推荐阅读