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.:
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
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.
After installing the library with npm, I have tried using import
and require()
statements in my App.js
file, without success:
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:
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
. 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
?
(For reference, the specific library I'm trying to use is https://github.com/WICG/focus-visible/.)