reactjsnpmbundlebrowserifyreactify

Size of bundled ReactJS app


I am trying to reduce the size of my reactjs application bundle.js file. For a relatively simple app i have its browserified js file size - 452Kb.

To build it, i use NPM with respective package.json file:

   {
      "name": "MyApp-React",
      "version": "0.0.1",
      "description": "My App Description",
      "main": "app.js",
      "scripts": {
        "watch": "watchify app.js -o public/js/bundle.js -v",
        "browserify": "browserify app.js | uglifyjs > public/js/bundle.js",
        "build": "npm run browserify",
        "start": "npm install"
      },
      "author": "",
      "dependencies": {
        "axios": "^0.14.0",
        "body-parser": "^1.15.2",
        "clipboard": "^1.5.12",
        "express": "~4.9.7",
        "express-handlebars": "~1.1.0",
        "express-session": "^1.14.1",
        "highlight.js": "^9.7.0",
        "node-jsx": "~0.12.4",
        "react": "~15.3.1",
        "react-dom": "^15.3.1",
        "react-maskedinput": "^3.2.4",
        "react-modal": "^1.4.0",
        "react-router": "^2.8.1"
      },
      "devDependencies": {
        "browserify": "~6.0.3",
        "nodemon": "^1.2.1",
        "reactify": "~1.1.1",
        "uglify-js": "~2.4.15",
        "watchify": "^3.1.1"
      },
      "browserify": {
        "debug": false,
        "transform": [
          "reactify"
        ]
      }
    }

Not being an expert in Node JS/ ReactJS development i hope i do somethin wrong, but i cant find what.

For the time being i tried few things: app.js file has a line of code setting NODE_ENV variable to 'production'

process.env.NODE_ENV = 'production';

A second thing i have tried is to use npm prune command with --production parameter. Having this run, i see it removes a lot from node_modules folder, but then npm run build is failing to run as it misses devDependencies. What can i do?


Solution

  • One thing that you could do to lighten the download burden for your users is get react and react-dom from a CDN instead of putting them in your bundle.

    Move them from the dependencies section of your package.json to a new section peerDependencies (see npm docs).

    Then add tags to your HTML code for loading React and ReactDOM like so:

    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min.js"></script>
    

    ā†’ See React on cdnjs.com

    Then you need to change your Browserify config to recognize react and react-dom as external modules.

    ā†’ See related question on StackOverflow