Reduce Browserify bundle of react.min.js and react-dom.min.js

后端 未结 1 1334
遇见更好的自我
遇见更好的自我 2021-01-15 02:46

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:



        
相关标签:
1条回答
  • 2021-01-15 03:11

    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
    
    0 讨论(0)
提交回复
热议问题