简体   繁体   中英

node.js load javascript library client side

I am fairly new to Node.js and I want to load a few javascript files in the browser but I can't seem to find anywhere how I can simply get libraries to be loaded inside the browser. So, my question is, how would I be able to load javascript libraries client side with Node.js?

I'm fairly new to node as well, but I've been using browserify to deal with node packages. There are a quite a few node packages that won't work in a browser - if they will work in a browser they will usually say it in their description.

Browserify is really easy to use - you just require() a module just as you would when writing a non-browser script (as far as I can tell). When you're ready to test the script on a browser, you just run

 browserify input.js -o output.js

and it pulls all of the dependencies from your require() 's into output.js, so then your require() s actually reference what you want it to.

--Updated for new comment--

As I see in your answer, you are talking about node.js packages? I am talking about standalone random javascript libraries (so, for example just one of my own js files that I want to load client side). Can you also load random javascript libraries with browserify? (I googled a bit but can't figure that out)

Yeah, you can do that; although I'm afraid I can't help you with the technicalities of it (like I said, new to it myself). Here's an example:

Bar.js (my library)

module.exports = bar; //tells node what to export in this file

var bar = {

  message: function(msg) {
    console.log(msg)
  }
}

Foo.js (my script)

var bar = require('./bar');
bar.message("foo"); //logs "foo" to console

And keep in mind that require() refers to a file. So Bar.js would need to be in the same directory as Foo.js . If Bar.js was in a different folder, you would just do require('./folder/bar') . To tie it all together, you would run browserify on Foo.js, and it would automatically grab Bar.js' contents.

There are a lot of different ways you can define exports, so you'll need to google around to see exactly how to do it for how your lib is formatted. But that's the gist of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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