2

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?

4
  • You'll have to provide more information Commented Mar 13, 2017 at 2:22
  • What other information you need? By the way, I can't do import from 'file.js'; because as I said, there are no exports code. (export const file = function(){...};) Commented Mar 13, 2017 at 2:27
  • In short, you can't. You can import a function for side effects, but you can't import and use a file's contents unless it's exporting something. Check this question for more: stackoverflow.com/questions/38172337/… Commented Mar 13, 2017 at 2:35
  • If I can't, how can I call the constructor in that file? and its methods? Commented Mar 13, 2017 at 2:40

1 Answer 1

3

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 };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.