Browserify: Use module.exports if required, otherwise expose global

前端 未结 4 1996
盖世英雄少女心
盖世英雄少女心 2021-01-31 08:09

I\'m considering adopting browserify for some of my projects, but would like to make sure that others don\'t have to use browserify if they want to use the (bundled) code. The o

相关标签:
4条回答
  • 2021-01-31 08:41

    There is a good article from Forbes Lindesay explaining how to do standalone builds: http://www.forbeslindesay.co.uk/post/46324645400/standalone-browserify-builds

    The short version, use the standalone option:

    browserify beep.js --standalone beep-boop > bundle.js
    
    0 讨论(0)
  • 2021-01-31 08:41

    Assuming another library hasn't created a global module.exports object, you can simply check for the existence of module.exports

    var mymodule = (function() { ... })();
    if (module && module.exports) {
      module.exports = mymodule;
    } else {
      window.mymodule = mymodule;
    }
    
    0 讨论(0)
  • 2021-01-31 08:44

    Why not just wrap the entire thing with a closure and pass exports as a parameter?

    (function (exports) {
        // code here
        // ...
        exports.foo = bar;
    })(exports || this);
    

    This way it will also export it to WebWorker scope and other 'windowless' environments.

    0 讨论(0)
  • 2021-01-31 08:45

    I'm dealing with the same problem building a library and here is a rought opinion. I think we need to separate first the audiences for a library in few categories:

    1. those who use browserify and NPM
    2. those who will just download a mylib.min.js and use one way or another
    3. AMD (with bower?), might be the third category.

    So, for 1 it is easy, you will have a your index.js module:

    module.exports = function () { /* code */ }
    

    and your package.json will have a main

    "main": "index.js"

    Notice I haven't add any window.xx code to index.js.

    For 2 I think the best idea is to create a standalone.js

    var mylib = require('./index.js');
    global.window.mylib = mylib;
    

    This is what browserify should build.

    For 3 (if you care about) you can tweak standalone.js as follows:

    var mylib = require('./index.js');
    if (typeof global.window.define == 'function' && global.window.define.amd) {
      global.window.define('mylib', function () { return mylib; });
    } else {
      global.window.mylib = mylib;
    }
    
    0 讨论(0)
提交回复
热议问题