简体   繁体   中英

How to import whole javascript file in React JS

I have a .js file (JavaScript file) that no exports code. It have a constructor and some prototype methods. I need this to add in the ReactJS App.

What I tried is, adding a script tag in client/index.html. Then upload the js file to client folder. When I call the constructor in my Apps.jsx file, I received an error, Constructor_name not defined.

How can I do it in correct way?

We do this in our project. You have to use a common object that both the browser and React share. So just create a reference into the window object.

import Foo from 'Foo';
import App from 'App';

//Foo.js
class Foo { constructor() {} }
window.Foo = Foo;

//App.jsx
let foo = new window.Foo();

If you have several you want to access and don't want to pollute the global scope:

//Foo.js
class Foo { constructor() {} }
window.MyApp = { Foo: Foo };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM