I want to bundle some React libs with Browserify and --require
them, but was put off by the file size.
I use the following Browserify command:
The problem is that Browserify is resolving the require
call(s) in react-dom
to the react
module in node_modules
. The package.json
for that module specifies main
as react.js
- so you end up with a bundle that contains the the non-minified source in addition to react.min.js
.
Note that if you bundle only react.min.js
:
browserify \
--require ./node_modules/react/dist/react.min.js:react \
> bundle-react.js
The bundle size is only slightly larger than react.min.js
:
ls -l node_modules/react/dist/react.min.js
... 21339 Dec 23 09:43 node_modules/react/dist/react.min.js
ls -l bundle-react.js
... 22006 Dec 23 11:56 bundle-react.js
To solve the problem, you need to tell Browserify to exclude react
and react-dom
, as you are going to provide an alternate mechanism for their being required - that is, you are going to specify the --require
option:
browserify \
--exclude react \
--require ./node_modules/react/dist/react.min.js:react \
--exclude react-dom \
--require ./node_modules/react-dom/dist/react-dom.min.js:react-dom \
> bundle-lib.js
The bundle size should now be much closer to the combined, minified files:
ls -l node_modules/react/dist/react.min.js
... 21339 Dec 23 09:43 node_modules/react/dist/react.min.js
ls -l node_modules/react-dom/dist/react-dom.min.js
... 123996 Dec 23 09:43 node_modules/react-dom/dist/react-dom.min.js
ls -l bundle-lib.js
... 146227 Dec 23 11:39 bundle-lib.js
You should then be able to create an application bundle that requires react
and react-dom
from your library bundle. Note that the Browserify command to create the application bundle should specify the --exclude
option for react
and react-dom
- so that they are required from the library bundle and not from node_modules
:
browserify \
--exclude react \
--exclude react-dom \
app.js > bundle-app.js