Reputation: 97
I'm working in a React.js project which I need to import some JavaScript in others, and some others I have to export it.
For example I have A.js
which needs some library:
var EventEmitter = require('EventEmitter');
var React = require('react');
//some code here
//some function definition
var fun = function(){...}
module.exports = fun;
And then I have another B.js
which needs not only libraries but also my own JavaScript. For example B.js
(I suppose both in the same folder):
var fun = require('./B.js');
var React = require('react');
//some other code here
I tried using the library requirejs and also try something with npm and nodejs but I'm not sure how it works. I'm using the flux-chat example
Upvotes: 3
Views: 9854
Reputation: 2373
First, if the code you specified for A.js
and B.js
aren't working for you, it would be because you're trying to require B.js
inside of itself... I think what you're trying to do is require A.js
into B.js
like so:
B.js
fix:
var fun = require('./A.js');
var React = require('react');
//some other code here
notice that fun
is requiring A.js
now
If the typo I noticed above isn't fixing your problem, continue reading on...
What exactly are you trying to do when you require A.js
into B.js
?
Without me knowing more of what you're trying to accomplish (or until I see the actual code inside of your A.js
and B.js
files), my best answer would be this:
A.js
would look something like:
module.exports = function(){
fun: function(param){...logic here...}
}
B.js
would look something like this:
var React = require('react');
var A = require('./B.js');
var Whatever = React.createClass({
render: function() {
return (
<div>
{A.fun('param value')}
</div>
);
}
});
If on the other hand, you're trying to export your A.js
as a React component that you can require and add to another (B.js
) React component... my answer would be different.
Upvotes: 0
Reputation: 735
RequireJS and npm are two different ways to resolve modules. People often use bower
to download AMD/UMD supported libs, and add the path to the config file of RequireJS. RequireJS resolves the dependencies for you.
I suggest that you use npm and webpack to manage your modules. There're also lots of documents for them.
Let's say you want to create a single page application. When you use npm to install a lib, it downloads from the npm registry into node_modules in your local disk. How do you indicate the path of node_modules/
folder in your html? The answer is you can't. Webpack does the task for you.
Webpack bundle all your javascript files and necessary dependencies (files in your local node_modules) into a big file. Then you can set the path to the <script src="...">
in your html.
Upvotes: -1