Rollup with React vendor splitting












0















I'm experimenting with using Rollup as a React toolset. I've got a working prototype when I can use lazy loading in react. I'm just working with just ES6 Modules, I'll integrate SystemJS for older browsers later. My question is regarding the rollup setup. It seems crazy to treat react and react-dom as internal, then have to supply a manualChunk and split them out again.



If I treat them as external and not chunk them I get the following error:



Uncaught (in promise) TypeError: Failed to resolve module specifier "react-dom". Relative references must start with either "/", "./", or "../".


Is there any way to treat react and react-dom as external and reference them from a CDN?



import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import replace from "rollup-plugin-replace";

export default {
input: ['src/index.js'],
output: {
format: 'esm',
dir: 'build',
},

experimentalCodeSplitting: true,

// Is there any way to avoid this?
manualChunks: {
'react': ['./node_modules/react/index.js'],
'reactDOM': ['./node_modules/react-dom/index.js'],
},
plugins: [
json(),
commonjs({
include: 'node_modules/**',
sourceMap: false,
namedExports: {
'./node_modules/react/index.js': ['Component','Children','PropTypes','createElement','cloneElement', 'createFactory'],
'./node_modules/react-dom/index.js': ['render'],
},
}),
nodeResolve(),
babel({
exclude: 'node_modules/**',
}),
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
})
],
// If react is treated as external, how can it be loaded into this ESM module from a UMD?
// e.g. "https://unpkg.com/react@16/umd/react.development.js"
// external: ['react','react-dom'],
};


Here's the react component setup, moduleA.js is lazy loaded on click:



// src/moduleA.js
const moduleA = 'Hello';
export default { moduleA };

// src/App.js
import React, { Component } from 'react';
import { version } from '../package.json';

export default class App extends Component {
constructor(props) {
super(props);
this.state = {
};
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
import('./moduleA')
.then((module) => {
console.log(module.default);
})
.catch(err => {
// Handle failure
});
};

render() {
return (
<React.Fragment>
<div className="App">
<h1>Hello, World!</h1>
<p>This is version: { version }</p>
</div>
<button onClick={this.handleClick}>Load</button>
</React.Fragment>
);
}
}

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));


//html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>#</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<main id="root"></main>
<!-- How can these be referenced in the below module?
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
-->
<script type="module">
import('/index.js');
</script>
</body>
</html>









share|improve this question



























    0















    I'm experimenting with using Rollup as a React toolset. I've got a working prototype when I can use lazy loading in react. I'm just working with just ES6 Modules, I'll integrate SystemJS for older browsers later. My question is regarding the rollup setup. It seems crazy to treat react and react-dom as internal, then have to supply a manualChunk and split them out again.



    If I treat them as external and not chunk them I get the following error:



    Uncaught (in promise) TypeError: Failed to resolve module specifier "react-dom". Relative references must start with either "/", "./", or "../".


    Is there any way to treat react and react-dom as external and reference them from a CDN?



    import commonjs from 'rollup-plugin-commonjs';
    import nodeResolve from 'rollup-plugin-node-resolve';
    import babel from 'rollup-plugin-babel';
    import json from 'rollup-plugin-json';
    import replace from "rollup-plugin-replace";

    export default {
    input: ['src/index.js'],
    output: {
    format: 'esm',
    dir: 'build',
    },

    experimentalCodeSplitting: true,

    // Is there any way to avoid this?
    manualChunks: {
    'react': ['./node_modules/react/index.js'],
    'reactDOM': ['./node_modules/react-dom/index.js'],
    },
    plugins: [
    json(),
    commonjs({
    include: 'node_modules/**',
    sourceMap: false,
    namedExports: {
    './node_modules/react/index.js': ['Component','Children','PropTypes','createElement','cloneElement', 'createFactory'],
    './node_modules/react-dom/index.js': ['render'],
    },
    }),
    nodeResolve(),
    babel({
    exclude: 'node_modules/**',
    }),
    replace({
    'process.env.NODE_ENV': JSON.stringify('development'),
    })
    ],
    // If react is treated as external, how can it be loaded into this ESM module from a UMD?
    // e.g. "https://unpkg.com/react@16/umd/react.development.js"
    // external: ['react','react-dom'],
    };


    Here's the react component setup, moduleA.js is lazy loaded on click:



    // src/moduleA.js
    const moduleA = 'Hello';
    export default { moduleA };

    // src/App.js
    import React, { Component } from 'react';
    import { version } from '../package.json';

    export default class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
    };
    this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
    import('./moduleA')
    .then((module) => {
    console.log(module.default);
    })
    .catch(err => {
    // Handle failure
    });
    };

    render() {
    return (
    <React.Fragment>
    <div className="App">
    <h1>Hello, World!</h1>
    <p>This is version: { version }</p>
    </div>
    <button onClick={this.handleClick}>Load</button>
    </React.Fragment>
    );
    }
    }

    // src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';

    ReactDOM.render(<App />, document.getElementById('root'));


    //html
    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>#</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

    <body>
    <main id="root"></main>
    <!-- How can these be referenced in the below module?
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    -->
    <script type="module">
    import('/index.js');
    </script>
    </body>
    </html>









    share|improve this question

























      0












      0








      0








      I'm experimenting with using Rollup as a React toolset. I've got a working prototype when I can use lazy loading in react. I'm just working with just ES6 Modules, I'll integrate SystemJS for older browsers later. My question is regarding the rollup setup. It seems crazy to treat react and react-dom as internal, then have to supply a manualChunk and split them out again.



      If I treat them as external and not chunk them I get the following error:



      Uncaught (in promise) TypeError: Failed to resolve module specifier "react-dom". Relative references must start with either "/", "./", or "../".


      Is there any way to treat react and react-dom as external and reference them from a CDN?



      import commonjs from 'rollup-plugin-commonjs';
      import nodeResolve from 'rollup-plugin-node-resolve';
      import babel from 'rollup-plugin-babel';
      import json from 'rollup-plugin-json';
      import replace from "rollup-plugin-replace";

      export default {
      input: ['src/index.js'],
      output: {
      format: 'esm',
      dir: 'build',
      },

      experimentalCodeSplitting: true,

      // Is there any way to avoid this?
      manualChunks: {
      'react': ['./node_modules/react/index.js'],
      'reactDOM': ['./node_modules/react-dom/index.js'],
      },
      plugins: [
      json(),
      commonjs({
      include: 'node_modules/**',
      sourceMap: false,
      namedExports: {
      './node_modules/react/index.js': ['Component','Children','PropTypes','createElement','cloneElement', 'createFactory'],
      './node_modules/react-dom/index.js': ['render'],
      },
      }),
      nodeResolve(),
      babel({
      exclude: 'node_modules/**',
      }),
      replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
      })
      ],
      // If react is treated as external, how can it be loaded into this ESM module from a UMD?
      // e.g. "https://unpkg.com/react@16/umd/react.development.js"
      // external: ['react','react-dom'],
      };


      Here's the react component setup, moduleA.js is lazy loaded on click:



      // src/moduleA.js
      const moduleA = 'Hello';
      export default { moduleA };

      // src/App.js
      import React, { Component } from 'react';
      import { version } from '../package.json';

      export default class App extends Component {
      constructor(props) {
      super(props);
      this.state = {
      };
      this.handleClick = this.handleClick.bind(this);
      }

      handleClick() {
      import('./moduleA')
      .then((module) => {
      console.log(module.default);
      })
      .catch(err => {
      // Handle failure
      });
      };

      render() {
      return (
      <React.Fragment>
      <div className="App">
      <h1>Hello, World!</h1>
      <p>This is version: { version }</p>
      </div>
      <button onClick={this.handleClick}>Load</button>
      </React.Fragment>
      );
      }
      }

      // src/index.js
      import React from 'react';
      import ReactDOM from 'react-dom';
      import App from './App';

      ReactDOM.render(<App />, document.getElementById('root'));


      //html
      <!doctype html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>#</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      </head>

      <body>
      <main id="root"></main>
      <!-- How can these be referenced in the below module?
      <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
      <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
      -->
      <script type="module">
      import('/index.js');
      </script>
      </body>
      </html>









      share|improve this question














      I'm experimenting with using Rollup as a React toolset. I've got a working prototype when I can use lazy loading in react. I'm just working with just ES6 Modules, I'll integrate SystemJS for older browsers later. My question is regarding the rollup setup. It seems crazy to treat react and react-dom as internal, then have to supply a manualChunk and split them out again.



      If I treat them as external and not chunk them I get the following error:



      Uncaught (in promise) TypeError: Failed to resolve module specifier "react-dom". Relative references must start with either "/", "./", or "../".


      Is there any way to treat react and react-dom as external and reference them from a CDN?



      import commonjs from 'rollup-plugin-commonjs';
      import nodeResolve from 'rollup-plugin-node-resolve';
      import babel from 'rollup-plugin-babel';
      import json from 'rollup-plugin-json';
      import replace from "rollup-plugin-replace";

      export default {
      input: ['src/index.js'],
      output: {
      format: 'esm',
      dir: 'build',
      },

      experimentalCodeSplitting: true,

      // Is there any way to avoid this?
      manualChunks: {
      'react': ['./node_modules/react/index.js'],
      'reactDOM': ['./node_modules/react-dom/index.js'],
      },
      plugins: [
      json(),
      commonjs({
      include: 'node_modules/**',
      sourceMap: false,
      namedExports: {
      './node_modules/react/index.js': ['Component','Children','PropTypes','createElement','cloneElement', 'createFactory'],
      './node_modules/react-dom/index.js': ['render'],
      },
      }),
      nodeResolve(),
      babel({
      exclude: 'node_modules/**',
      }),
      replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
      })
      ],
      // If react is treated as external, how can it be loaded into this ESM module from a UMD?
      // e.g. "https://unpkg.com/react@16/umd/react.development.js"
      // external: ['react','react-dom'],
      };


      Here's the react component setup, moduleA.js is lazy loaded on click:



      // src/moduleA.js
      const moduleA = 'Hello';
      export default { moduleA };

      // src/App.js
      import React, { Component } from 'react';
      import { version } from '../package.json';

      export default class App extends Component {
      constructor(props) {
      super(props);
      this.state = {
      };
      this.handleClick = this.handleClick.bind(this);
      }

      handleClick() {
      import('./moduleA')
      .then((module) => {
      console.log(module.default);
      })
      .catch(err => {
      // Handle failure
      });
      };

      render() {
      return (
      <React.Fragment>
      <div className="App">
      <h1>Hello, World!</h1>
      <p>This is version: { version }</p>
      </div>
      <button onClick={this.handleClick}>Load</button>
      </React.Fragment>
      );
      }
      }

      // src/index.js
      import React from 'react';
      import ReactDOM from 'react-dom';
      import App from './App';

      ReactDOM.render(<App />, document.getElementById('root'));


      //html
      <!doctype html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>#</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      </head>

      <body>
      <main id="root"></main>
      <!-- How can these be referenced in the below module?
      <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
      <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
      -->
      <script type="module">
      import('/index.js');
      </script>
      </body>
      </html>






      javascript reactjs rollup






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 4:16









      sansSpoonsansSpoon

      633416




      633416
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405177%2frollup-with-react-vendor-splitting%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405177%2frollup-with-react-vendor-splitting%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          'app-layout' is not a known element: how to share Component with different Modules

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          WPF add header to Image with URL pettitions [duplicate]