How do I exclude the “require('react')” from my Browserified bundle?

前端 未结 4 1318
失恋的感觉
失恋的感觉 2020-12-14 09:11

I\'m using Browserify to bundle a ReactJS application.

All my components include a require(\"react\") at the top. This causes

4条回答
  •  醉话见心
    2020-12-14 09:30

    @NickTomlin gave this answer, but then deleted it.


    You can use external:

    browserify --external react src.js > dest.js

    An example using the api:

    var bundler = browserify('src.js');
    
    bundler.external('react');
    bundler.bundle();
    

    This is a viable option. external requires another script to provide the module in a compatible way. You can produce such a script like this:

    browserify -r react > react.js
    env NODE_ENV=production browserify -r react | uglifyjs -m > react.min.js
    

    And in HTML:

    
    
    

    dest.js is your code except react. react.js is just react and its dependencies.

    Need more things external? Just add them in addition to react.

    browserify -x react -x react-bootstrap src.js > dest.js
    browserify -r react -r react-bootstrap > vendor.js
    

    You could also do something like this in package.json

    "browser": {"react": "./react-fake.js"}
    
    // ./react-fake.js
    try {
        module.exports = require('react');
    } catch(e){
        module.exports = window.React;
    }
    

    And compile with -x react. This allows you to accept a -r react build, and fallback to a global React.

提交回复
热议问题