[英]Import third-party JavaScript library that normally self-executes into React app (using create-react-app)
I'm trying to use a third-party library in my React app (built via create-react-app
) that is normally loaded via a <script>
tag in html file.: 我正在尝试在我的React应用程序(通过create-react-app
构建)中使用第三方库,该应用create-react-app
通常通过html文件中的<script>
标记加载:
index.html 的index.html
...
<script src="some-library.js"></script>
</body>
</html>
The script basically just calls itself at the end of the file: 该脚本基本上只是在文件末尾调用自己:
some-library.js 一些-library.js
function foo() {
...
}
foo();
There are no modules or export
statements, so it's not immediately clear to me how to use this in my React app. 没有模块或export
语句,因此我不能立即清楚如何在我的React应用程序中使用它。
After installing the library with npm, I have tried using import
and require()
statements in my App.js
file, without success: 在使用npm安装库之后,我尝试在App.js
文件中使用import
和require()
语句,但没有成功:
App.js App.js
import "some-library"; // doesn't work
require("some-library"); // doesn't work
const SomeLibrary = require("some-library"); // doesn't work
...
Some instructions about using third-party libraries in React suggest using the library within one of the React lifecycle hooks, like componentDidMount()
, but there's no function I'm able to call from the library: 关于在React中使用第三方库的一些说明建议在其中一个React生命周期钩子中使用该库,比如componentDidMount()
,但是我没有能够从库中调用的函数:
App.js 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;
The only solution I've been able to find is to copy some-library.js
into my public/
folder, and then include it as a <script>
tag in index.html
. 我能找到的唯一解决方案是将some-library.js
复制到我的public/
文件夹中,然后将其作为index.html
的<script>
标记包含在内。 This seems like an awkward solution though. 这似乎是一个尴尬的解决方案。
Is there a way to import this library in my src/
JavaScript files for React instead of just as a <script>
tag in index.html
? 有没有办法在我的src/
JavaScript文件中为React导入这个库,而不是像index.html
的<script>
标签一样?
(For reference, the specific library I'm trying to use is https://github.com/WICG/focus-visible/ .) (作为参考,我尝试使用的特定库是https://github.com/WICG/focus-visible/ 。)
I was able to get this working by directly importing the file from the library's dist
folder, instead of just naming the library by itself. 我能够通过直接从库的dist
文件夹导入文件来实现这一点,而不是仅仅自己命名库。
I also needed to make sure to import the library first before any other libraries (eg React
). 我还需要确保在任何其他库(例如React
)之前首先导入库。
App.js App.js
import "some-library/dist/some-library.js";
import React, { Component } from "react";
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.