Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid React loading twice with Webpack when developing

Given the following directory structure:

my-project | |-- node_modules     |     |-- react     |-- module-x         |         |--node_modules             |             |--react 

You can see both my-project and module-x require React. I have the same problem as described on this question, but the suggestion is to remove react from the package.json dependencies. I do that and it works fine, as long as no node_modules are installed in module-x, because Webpack will use React from my-project. But if I'm in the process of developing module-x and the node_modules are installed, Webpack uses React from both my-project and module-x.

Is there a way I could have Webpack make sure only one instance of React is used, even though it's required on two separate levels?

I know I could keep module-x in a separate directory when developing, but it seems like I'd have to publish it and then install it in my-project to test it, and that's not very efficient. I thought about npm link, but had no luck with it since it still has node_modules installed in module-x.

This here sounds a lot like the same challenge I'm having, but it doesn't seem like npm dedupe or Webpack's dedupe option would work. I'm probably not understanding some important detail.

like image 561
chevin99 Avatar asked Jul 01 '15 19:07

chevin99


People also ask

Why use webpack instead of create React app?

Configuring webpack provides complete control over the development environment, while initializing with Create React App prevents any custom configuration by default.

Is it necessary to use webpack in react JS?

Well, we don't necessarily need webpack to work with React, other alternatives could be Browserify, Parsel, Brunch, etc, but honestly, I don't know how well they fit in with React. js. Webpack is the most widely used and an accepted module bundler and task runner throughout React. js community.

How do I unlink a node module?

You can “undo” the effects of npm link by simply removing the symbolic links. But there is a built in command for it, aptly called: npm unlink . Just run npm unlink --no-save <module_name> on your project's directory to remove the local symlink, and run npm unlink on the module's directory to remove the global symlink.


1 Answers

This issue usually arises when using npm link. A linked module will resolve its dependencies in its own module tree, which is different from the one of the module that required it. As such, the npm link command installs peerDependencies as well as dependencies.

You can use resolve.alias to force require('react') to resolve to your local version of React.

resolve: {   alias: {     react: path.resolve('./node_modules/react'),   }, }, 
like image 135
Alexandre Kirszenberg Avatar answered Oct 03 '22 09:10

Alexandre Kirszenberg