Browserify - call a function associated with a file created using a browser in a browser

I am new to nodejs and browning. I started with this one.

I have a main.js file that contains this code

var unique = require('uniq'); var data = [1, 2, 2, 3, 4, 5, 5, 5, 6]; this.LogData =function(){ console.log(unique(data)); }; 

Now I install the uniq module with npm number:

  npm install uniq 

Then I collect all the necessary modules, starting with main.js, into a single file called bundle.js using the browser command:

 browserify main.js -o bundle.js 

The generated file is as follows:

 (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var unique = require('uniq'); var data = [1, 2, 2, 3, 4, 5, 5, 5, 6]; this.LogData =function(){ console.log(unique(data)); }; },{"uniq":2}],2:[function(require,module,exports){ "use strict" function unique_pred(list, compare) { var ptr = 1 , len = list.length , a=list[0], b=list[0] for(var i=1; i<len; ++i) { b = a a = list[i] if(compare(a, b)) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } function unique_eq(list) { var ptr = 1 , len = list.length , a=list[0], b = list[0] for(var i=1; i<len; ++i, b=a) { b = a a = list[i] if(a !== b) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } function unique(list, compare, sorted) { if(list.length === 0) { return [] } if(compare) { if(!sorted) { list.sort(compare) } return unique_pred(list, compare) } if(!sorted) { list.sort() } return unique_eq(list) } module.exports = unique },{}]},{},[1]) 

After including the bundle.js file in my index.htm page, how do I call the logData function?

+74
npm browserify
Apr 25 '14 at 2:35
source share
10 answers

By default, the browser does not allow you to access the modules due to the scroll code - if you want to call the code in the browser, you must scroll the code along with the module. See http://browserify.org/ for an example.

Of course, you can also explicitly make your method accessible from outside, like this:

 window.LogData =function(){ console.log(unique(data)); }; 

You can then call LogData() from anywhere on the page.

+68
Apr 25 '14 at
source share

A key part of bundling stand-alone modules with Browserify is the --s option. It provides everything that you export from your module, using node module.exports as a global variable. You can then include the file in the <script> .

You only need to do this if for some reason you need this global variable. In my case, the client needs a separate module that can be included in web pages without having to worry about this Browserify business.

In this example, we use the --s option with the module argument:

 browserify index.js --s module > dist/module.js 

This will open our module as a global variable called module .
Source

Update: Thanks @fotinakis. Make sure you pass --standalone your-module-name . If you forget that --standalone accepts an argument, Browserify can silently generate an empty module because it could not find it.

Hope this saves you some time.

+86
Mar 02 '15 at 8:42
source share

The @ Matas Vaitkevicius answer with the standalone Browserify option is correct (@thejh's answer using the global variable window also works, but as others have noted, it pollutes the global namespace, so it is not perfect). I would like to add a little more information on how to use the standalone option.

In the source script that you want to link, do not forget to expose the functions you want to call through module.exports. In a client script, you can call these public functions through <package name>. <Function Name> . Here is an example:

My src / script.js source file will have this:
module.exports = {myFunc: func};

My browserify command will look something like this:
browserify src/script.js --standalone myBundle > dist/bundle.js

And my client script dist / client.js will load the attached script
<script src="bundle.js"></script>
and then call the exposed function as follows:
<script>myBundle.myFunc();</script>




There is no need to require the package name in the client script before calling the provided functions, for example <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> not required and will not work.

In fact, like all browserify-related functions without offline mode, the require function will not be available outside the built-in script . Browserify allows you to use some Node features on the client side, but only in the script itself; this did not mean creating a separate module that you can import and use anywhere on the client side, so we need to go for all these additional problems, just to call one function out of its associated context.

+22
Apr 04 '17 at 19:22
source share

Read your browser README.md for the --standalone or google "browserify umd" option

+7
Jul 01 '14 at 16:35
source share

I just read the answers and it looks like no one mentioned using the scope global variable? Which is useful if you want to use the same code in node.js and in the browser.

 class Test { constructor() { } } global.TestClass = Test; 

Then you can access TestClass anywhere.

 <script src="bundle.js"></script> <script> var test = new TestClass(); // Enjoy! </script> 

Note TestClass is available everywhere. Which is similar to using a window variable.

Alternatively, you can create a decorator that provides a global scope class. Which is really good, but it makes it difficult to track where the variable is defined.

+6
May 13 '17 at 2:44
source share

You have several options:

  • Let the browserify-bridge plugin automatically export the modules to the generated input module. This is useful for SDK projects or situations where you do not need to manually monitor what is exported.

  • Follow the pseudo-namespace template for showdown:

First arrange your library using the benefits of indexing in folders:

 /src --entry.js --/helpers --- index.js --- someHelper.js --/providers --- index.js --- someProvider.js ... 

Using this template, you define an entry as follows:

 exports.Helpers = require('./helpers'); exports.Providers = require('./providers'); ... 

Note that the requirement automatically loads index.js from each corresponding subfolder

In your subfolders, you can simply include a similar manifest of available modules in this context:

 exports.SomeHelper = require('./someHelper'); 

This template scales very well and allows you to track contextual (folders by folders), which is included in the minimized api.

+1
Aug 12 '15 at 21:06
source share

I need time to figure out and understand this problem even with these answers

it's really easy - it's about packaging

for this, I assume that you have only 1 script for the entire application {{app_name}}

1 alternative

add function to "this" object

 function somefunction(param) {} -> this.somefunction = function(param) {} 

then you should name this object as accessible - you will do this by adding the parameter "standalone with name", as others advise

so if you use watchify with browserify use this

 var b = browserify({ ... standalone: '{{app_name}}' }); 

or command line

 browserify index.js --standalone {{app_name}} > index-bundle.js 

then you can call your function from the browser

 app_name.somefunction(param); window.app_name.somefunction(param); 

2 options

add function to window object

 function somefunction(param) {} -> window.somefunction = function(param) {} 

then you can call your function from the browser

 somefunction(param); window.somefunction(param); 

-

maybe i will help someone

0
Jan 22 '19 at 12:12
source share

To make your function accessible both from HTML and from the server node:

main.js:

 var unique = require('uniq'); function myFunction() { var data = [1, 2, 2, 4, 3]; return unique(data).toString(); } console.log ( myFunction() ); // When browserified - we can't call myFunction() from the HTML, so we'll externalize myExtFunction() // On the server-side "window" is undef. so we hide it. if (typeof window !== 'undefined') { window.myExtFunction = function() { return myFunction(); } } 

main.html:

 <html> <head> <script type='text/javascript' src="bundle.js"></script> <head> <body> Result: <span id="demo"></span> <script>document.getElementById("demo").innerHTML = myExtFunction();</script> </body> </html> 

Run:

 npm install uniq browserify main.js > bundle.js 

and you should get the same results when opening main.html in the browser as when you start

 node main.js 
0
Aug 08 '19 at 17:24
source share

For debugging purposes, I added this line to my code.js code:

 window.e = function(data) {eval(data);}; 

Then I could run anything even outside the package.

 e("anything();"); 
-one
Jul 23 '17 at 22:11
source share
 window.LogData =function(data){ return unique(data); }; 

Call the function simply by LogData(data)

This is just a small modification of thejh in response, but an important one

-one
May 01 '18 at 8:56
source share



All Articles