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

前端 未结 11 2224
-上瘾入骨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 18:05

    Minimal runnable example

    This is basically the same as: https://stackoverflow.com/a/43215928/895245 but with concrete files that will allow you to just run and easily reproduce it yourself.

    This code is also available at: https://github.com/cirosantilli/browserify-hello-world

    index.js

    const uniq = require('uniq');
    
    function myfunc() {
      return uniq([1, 2, 2, 3]).join(' ');
    }
    exports.myfunc = myfunc;
    

    index.html

    
    
    
    
    Browserify hello world
    
    
    

    Node.js usage:

    #!/usr/bin/env node
    
    const browserify_hello_world = require('./index.js');
    
    console.log(browserify_hello_world.myfunc());
    

    Generate out.js for browser usage:

    npx browserify --outfile out.js --standalone browserify_hello_world index.js
    

    Both the browser and the command line show the expected output:

    1 2 3
    

    Tested with Browserify 16.5.0, Node.js v10.15.1, Chromium 78, Ubuntu 19.10.

提交回复
热议问题