将通常自执行的第三方 JavaScript 库导入 React 应用程序(使用 create-react-app)

Import third-party JavaScript library that normally self-executes into React app (using create-react-app)

我正在尝试在我的 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/ 文件夹中,然后将其作为 <script> 标记包含在 index.html 中.不过,这似乎是一个尴尬的解决方案。

有没有办法在我的 src/ JavaScript 文件中为 React 导入这个库,而不仅仅是 index.html 中的 <script> 标签?

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

我能够通过直接从库的 dist 文件夹中导入文件来实现这一点,而不是仅仅自己命名库。

我还需要确保先导入该库,然后再导入任何其他库(例如 React)。

App.js

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