简体   繁体   English

如何在React JS中导入整个JavaScript文件

[英]How to import whole javascript file in React JS

I have a .js file (JavaScript file) that no exports code. 我有一个.js文件(JavaScript文件),没有导出代码。 It have a constructor and some prototype methods. 它有一个构造函数和一些原型方法。 I need this to add in the ReactJS App. 我需要在ReactJS App中添加它。

What I tried is, adding a script tag in client/index.html. 我试过的是在client / index.html中添加一个脚本标记。 Then upload the js file to client folder. 然后将js文件上传到客户端文件夹。 When I call the constructor in my Apps.jsx file, I received an error, Constructor_name not defined. 当我在Apps.jsx文件中调用构造函数时,收到错误,Constructor_name未定义。

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. 您必须使用浏览器和React都共享的公共对象。 So just create a reference into the window object. 因此,只需在window对象中创建引用即可。

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 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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