Reputation: 72001
My goal is to figure out how I can use node modules in an existing javascript application
My existing application is jQuery and ReactJS based.
I've come across a few node modules I'd like to start using with the project, that appear to be only available as modules (so they can't be used by simply adding a script
tag).
Previously I'd been using bower
to install libraries and use them locally simply using script
tags.
I understand that I can use Browserify
or Webpack
to bundle a bunch of Node modules up into a single javascript file, but how can I expose the modules that are in it to my existing app?
What'd I'd like to be able to do is
<script src="jquery.min.js"/>
<script src="bundle.js"/>
<script src="myapp.js"/>
where myapp.js
can use a global variable for say module_x
which was an npm module.
One of the problems I foresee is that say bundle.js
may include jquery already, so how do I address this as well? I know some may say "convert your whole project to modules", then it'll just work! But I'm wondering if it can be done without doing that, despite all the benefits ;-)
Upvotes: 2
Views: 469
Reputation: 7336
Its not the better practice, but you can use globals with browserify. This way you will be able to access libraries you get with require()
in any scope you need. Just use:
global.lib = require('somelib');
Then just browserify your source file throught browserify. If you dont know how, just read the documentation. Its pretty easy to use.
After that, just access lib
from anywhere you need it.
Also, if you already defined jQuery as a global previous to the bundle, you will be able to access it into the browserified file. Inside your main browserify file, just:
var someVar = require('./somefile.js');
var allDivs = $("div"); // $ was a global before this file runs
Upvotes: 3