0

New to browserify: I have a normal js file with some react components grouped in a namespace like:

var myNameSpace= {
'reactFunc1': React....,
'reactFunc2': React....,
'reactFunc3': React....,
'nonreactFunc1' function(..)
}

And in some other js file I'm trying to use:

myNameSpace.reactFunc1(...);

this works fine when I tranform jsx to js using babel.

But when I browerify the files using the command browserify -t [ babelify --presets [ react ] ] some.js someOther.js

myNameSpace not defined

What I'm doing wrong here. Is there any way to get this working without much hastle / code change?

4
  • Are you using the namespace on a different module? How are you importing the namespace? Commented Apr 13, 2016 at 6:43
  • @Tzach I'm not importing it. And there is no module here.. I have 2 seperate js files... when I don't browserify the files... myNameSpace.reactFunc1 is defined but when I browserify myNameSpace.reactFunc2 is undefined Commented Apr 13, 2016 at 6:48
  • I'm not sure how to make this var myNameSpace= { 'reactFunc1': React...., 'reactFunc2': React...., 'reactFunc3': React...., 'nonreactFunc1' function(..) } as module and export it with name myNameSpace and use this in other js file and do something like myNameSpace.reactFunc1(...); Commented Apr 13, 2016 at 6:49
  • Got you. That's because when using browserify each file is a module, and the var definitions are local to that module. You'll need to import one module into the other, or do window.myNameSpace = ... Commented Apr 13, 2016 at 6:50

1 Answer 1

2

You have two options here, using modules or using the global namespace.

When using modules, you will need to export the namespace from the first module and require it in the other module:

module.exports = {
    'reactFunc1': React....,
}

Then in the other file

var myNameSpace = require('first_module');

The other option (less preferred) is to use the global window object:

window.myNameSpace = {
    'reactFunc1': React....,
}

Then in the other file:

window.myNameSpace.reactFunc1()
Sign up to request clarification or add additional context in comments.

1 Comment

@NishanthMatha Give your modules meaningful names, that way it's easier to keep in mind what does what.

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.