Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Browserify to bundle a ReactJS application.

All my components include a require("react") at the top. This causes Browserify to include the ReactJS source in my bundle. But I'd like to exclude it.

How do I do that? Is this the right thing to do?

like image 906
André Pena Avatar asked Mar 24 '15 00:03

André Pena


People also ask

What is Browserify in react?

Browserify allows us to use Node-style modules in the browser. Normally when we want to include some library code in our project, we include another script tag on the page.

Can I use require in react?

require is not a React api, nor is it a native browser api (for now). require comes from commonjs and is most famously implemented in node. js, if you have used node. js, you will see requires everywhere.

Why we use npm in react?

It's because of two main reasons: Using an NPM (Node Package Manager), Node works alongside the NPM registry to easily install any package through the NPM CLI. Node bundles a React application into a single file for easy compilation using webpack and several other Node modules.

What is Webpack in react?

Like create-React-app, React Webpack is also a command-line tool used to create a bundle of assets (files and code). It doesn't run on the browser or the server. It takes all the JS files and other assets, transforming them into one large file.


1 Answers

@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:

<script src="react.js"></script>
<script src="dest.js"></script>

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.

like image 86
Brigand Avatar answered Oct 11 '22 16:10

Brigand