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

前端 未结 11 2190
-上瘾入骨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条回答
  •  萌比男神i
    2020-11-29 18:00

    it's really simple -- this whole concept is about wrapping

    1. alternative - object "this"

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

    add function {{function_name}} to object "this"

    function {{function_name}}(param) {}
    ->
    this.{{function_name}} = 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}}.{{function_name}}(param);
    window.{{app_name}}.{{function_name}}(param);
    

    2. alternative - object "window"

    add function {{function_name}} to object "window"

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

    then you can call your function from browser

    {{function_name}}(param);
    window.{{function_name}}(param);
    

    --

    maybe I help someone

提交回复
热议问题