Browserifying react with addons to a standalone component, usable by plugins

北战南征 提交于 2019-12-05 05:35:19

Notice that what you want to achieve is documented here: Browserify partitionning

I'm packaging my app in 2 parts: appLibs.js and app.js. I've done this for caching too but I choose to put all the code that does not change often in a single bundle instead of splitting it like you want, but you can use the same trick.

Here's the code that might interest you:

var libs = [
    "react",
    "react/addons", // See why: https://github.com/substack/node-browserify/issues/1161
    ... other libs
];

gulp.task('browserify-libs', function () {
    var b = browserify(...);
    libs.forEach(function(lib) {
        b.require(lib);
    });
    return b.bundle().......
});
gulp.task('browserify',['browserify-libs'],function () {
    var b = browserify(...);
    libs.forEach(function(lib) {
        b.external(lib);
    });
    return b.bundle().......
});

This way, React is only bundled once in appLibs.js and can be required inside app.js using both react and react/addons

If you really want to bundle your libs in separate files, bundle then with b.require("myLib"), but in this case be sure to check that the libraries do not have direct dependencies. If a lib to bundle has a dependency in React, this means that lib will be packaged in the bundle, potentially leading to multiple bundles having React inside them (and making weird failures at runtime). The library should rather use peerDependencies so that b.require does not try to package these dependencies

Sounds like the perfect use case for factor-bundle.

From the browserify handbook:

factor-bundle splits browserify output into multiple bundle targets based on entry-point. For each entry-point, an entry-specific output file is built. Files that are needed by two or more of the entry files get factored out into a common bundle.

Thanks for all suggestions but the solution I have chosen is a "shim" if that is the correct term. Looks like this:

  1. Browserify react/addons into it's own file
  2. Create my own file (called shim) only containing this: module.exports = require('react/addons');
  3. Browserify my shim and use the expose option, exposing it as react

Now, either if react or react/addons is required I get react/addons

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