1

I have a special scenario. One web application is built upon React. Another JavaScript utility is on React, but that utility is loaded by script tag. So, the application and the utility is built isolatedly. As a result, both the web application bundle file and utility bundle file have React built inside.

Now, we want to make them share one copy of React. It is preferred to export React as global variable in web application code(e.g. global.React) so that the utility can use it directly.

The code in utility is still like below. Hopefully, webpack can ignore it and import React from global.React.

import React from 'react';
import ReactDOM from 'react-dom';

The question is: how to config webpack to tell the utiltiy not to bundle React?

1 Answer 1

1

Tested with some non-React application:

  • in index.html import React from CDN, this will define global React.

    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>

  • somewhere in application doing as below, resolves to React instance:

    declare var React; console.log('React is ', React);

So if your first bundle, registers React globally, you may use it.

Just keep in mind, that it considered as bad practice to import from global like this. It beats whole concept of webpack's modularity. For instance, if your first module, upgrades to some backward incompatible version of React, your second module will break eventually as well.

For small projects, might be ok.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.