【问题标题】:Import third-party JavaScript library that normally self-executes into React app (using create-react-app)将通常自执行的第三方 JavaScript 库导入 React 应用程序(使用 create-react-app)
【发布时间】:2018-09-01 08:01:51
【问题描述】:

我正在尝试在我的 React 应用程序(通过 create-react-app 构建)中使用第三方库,该库通常通过 html 文件中的 <script> 标记加载。:

index.html

    ...
    <script src="some-library.js"></script>
  </body>
</html>

脚本基本上只是在文件末尾调用自己:

some-library.js

function foo() {
  ...
}

foo();

没有模块或export 语句,所以我不清楚如何在我的 React 应用程序中使用它。

使用 npm 安装库后,我尝试在我的 App.js 文件中使用 importrequire() 语句,但没有成功:

App.js

import "some-library";                          // doesn't work
require("some-library");                        // doesn't work
const SomeLibrary = require("some-library");    // doesn't work

...

关于在 React 中使用第三方库的一些说明建议在 React 生命周期挂钩之一中使用该库,例如 componentDidMount(),但我无法从库中调用任何函数:

App.js

import React, { Component } from "react";
import * as SomeLibrary from "some-library";

class App extends Component {
  componentDidMount() {
    SomeLibrary.foo();  // doesn't work (wasn't exported in "some-library")
  }

  render() {
    ...
  }
}

export default App;

我能找到的唯一解决方案是将some-library.js 复制到我的public/ 文件夹中,然后将其作为&lt;script&gt; 标记包含在index.html 中。不过,这似乎是一个尴尬的解决方案。

有没有办法在我的 src/ JavaScript 文件中为 React 导入这个库,而不是仅仅作为 index.html 中的 &lt;script&gt; 标记?

(作为参考,我尝试使用的特定库是https://github.com/WICG/focus-visible/。)

【问题讨论】:

  • 我查看了文档,库似乎没有任何方法。如“用法”中所述,将脚本标签添加到您的公共索引中。然后添加 CSS 规则。据我所知,就是这样。但是,它很可能不适用于 React 应用程序,因为 React 会不断更改 DOM。
  • 感谢 Chris G,我能够通过导入 javascript 文件本身而不是仅在 node_modules 中命名 npm 包来使其工作。有关详细信息,请参阅下面的答案。

标签: javascript reactjs create-react-app


【解决方案1】:

我能够通过直接从库的 dist 文件夹中导入文件来实现此功能,而不仅仅是单独命名库。

我还需要确保在导入任何其他库之前先导入该库(例如React)。

App.js

import "some-library/dist/some-library.js";
import React, { Component } from "react";
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2022-08-02
    • 2020-10-21
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多