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

前端 未结 11 2163
-上瘾入骨i
-上瘾入骨i 2020-11-29 17:18

I am new to nodejs and browserify. I started with this link .

I have file main.js which contains this code

var unique = require(\'uniq\');

var data          


        
11条回答
  •  情深已故
    2020-11-29 17:58

    @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 .. 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

    and then call the exposed function like this:


    There's no need to require the bundle name in the client script before calling the exposed functions, e.g. 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.

提交回复
热议问题