Browserify - How to call function bundled in a file generated through browserify in browser

≡放荡痞女 提交于 2019-11-27 02:59:37

By default, browserify doesn't let you access the modules from outside of the browserified code – if you want to call code in a browserified module, you're supposed to browserify your code together with the module. See http://browserify.org/ for examples of that.

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

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

Then you could call LogData() from anywhere else on the page.

The key part of bundling standalone modules with Browserify is the --s option. It exposes whatever you export from your module using node's module.exports as a global variable. The file can then be included in a <script> tag.

You only need to do this if for some reason you need that global variable to be exposed. In my case the client needed a standalone module that could be included in web pages without them needing to worry about this Browserify business.

Here's an example where we use the --s option with an argument of module:

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

This will expose our module as a global variable named module.
Source.

Update: Thanks to @fotinakis. Make sure you're passing --standalone your-module-name. If you forget that --standalone takes an argument, Browserify might silently generate an empty module since it couldn't find it.

Hope this saves you some time.

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

In the source script that you want to bundle, make sure to expose the functions you want to call via module.exports. In the client script, you can call these exposed functions via <bundle-name>.<func-name>. Here's an example:

My source file src/script.js 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 bundled script
<script src="bundle.js"></script>
and then call the exposed function like this:
<script>myBundle.myFunc();</script>


There's no need to require the bundle name in the client script before calling the exposed functions, e.g. <script src="bundle.js"></script><script>var bundled = require("myBundle"); bundled.myFunc();</script> isn't necessary and won't work.

In fact, just like all functions bundled by browserify without standalone mode, the require function won't be available outside of the bundled script. Browserify allows you to use some Node functions client-side, but only in the bundled script itself; it's not meant to create a standalone module you can import and use anywhere client-side, which is why we have to go to all this extra trouble just to call a single function outside of its bundled context.

Read README.md of browserify about --standalone parameter or google "browserify umd"

I just read through the answers and seems like nobody mentioned the use of the global variable scope? Which is usefull 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 the TestClass anywhere.

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

Note: The TestClass then becomes available everywhere. Which is the same as using the window variable.

Additionally you can create a decorator that exposes a class to the global scope. Which is really nice but makes it hard to track where a variable is defined.

You have a few options:

  1. Let plugin browserify-bridge auto-export the modules to a generated entry module. This is helpful for SDK projects or situations where you don't have to manually keep up with what is exported.

  2. Follow a pseudo-namespace pattern for roll-up exposure:

First, arrange your library like this, taking advantage of index look-ups on folders:

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

With this pattern, you define entry like this:

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

Notice the require automatically loads the index.js from each respective sub-folder

In your subfolders, you can just include a similar manifest of the available modules in that context:

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

This pattern scales really well and allows for contextual (folder by folder) tracking of what to include in the rolled-up api.

it takes me a while figure out and understand this issue even with these answers

it's really simple - it's about wrapping

for this purpose I'll assume you have only 1 script for whole app {{app_name}}

1 alternative

add function to object "this"

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

then you have to name that object to be available - you will do it add param "standalone with name" like others advised

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 browser

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

2 alternative

add function to object "window"

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

then you can call your function from browser

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

--

maybe I help someone

To have your function available from both the HTML and from server-side 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 same results when opening main.html in a browser as when running

node main.js

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

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

Then I could run anything even outside the bundle.

e("anything();");
window.LogData =function(data){
   return unique(data);
};

Call the function simply by LogData(data)

This is just a slight modification to thejh's answer but important one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!