Search code examples
reactjsgulpwebpackbabeljscommonschunkplugin

Is there a way to load react library files separately and not in the bundled files when using react with babel, webpack and gulp as building tool?


I have an application where I have to build code using babel and react. The application will be built using gulp and webpack for automated build creation and deployment. When using gulp and webpack to convert babel+react code to browser interpretable code, we need to install react using npm and has to be imported in all files, following is the sample code:

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './helloWorld.jsx';
import HelloMe from './hello-me.jsx';

ReactDOM.render(
    <HelloWorld />,
    document.getElementById('app-test')
);

ReactDOM.render(
    <HelloMe />,
    document.getElementById('app-container')
);

Now, the problem is this code when bundled with webpack, bundles react and react-dom library code to the bundled file. So, I would not be able to cache these library files to be loaded in different views. Due to this, the same library code will load again and again in different bundled files. Is there a way to load these files separately and not in the bundled file?


Solution

  • Edit your Wabpack configuration file and specify React & ReactDOM as externals.

    externals: {
      "react": "React",
      "react-dom": "ReactDOM",
    },
    

    Then, include React & ReactDOM from CDN or your prefered source.

    Whenever you call import React from 'react' or require('react') (or react-dom), Webpack gives you external copy of library