How to avoid `loaded two copies of React` error when developing an external component?

前端 未结 9 1612
无人共我
无人共我 2020-12-28 14:05

I am developing an external component (let\'s say my-component, which I link to the project with npm link (as it is in process and I need the packa

相关标签:
9条回答
  • 2020-12-28 14:46

    The problem is with npm link. https://github.com/npm/npm/issues/5875

    npm doesn't treat the linked directory as a child of the parent project.

    Try alternatives to npm link:

    1) Use relative path dependencies in package.json

    2) Manually include your dependencies in your projects node_modules directory

    3) Use url path

    Basically anything but npm link

    0 讨论(0)
  • 2020-12-28 14:53

    I believe the answer is to specify react and react-dom as peerDependencies in your external component's package.json. As best as I can follow here and here, npm link should (as of npm@3) no longer install peerDependencies (or `devDependencies either).

    Aaaand I just read your post more carefully and realized that you already are specifying them as peerDependencies. Therefore, I think the answer boils down to:

    Upgrade to npm@3:

    npm install -g npm@3.0-latest

    0 讨论(0)
  • 2020-12-28 14:56

    If you're using Webpack in the main project, this solution may work. In my case, project-a requires project-b. Both require React and ReactDOM 0.14.x

    I have this in project-a/webpack.config.js:

    resolve: {
      modulesDirectories: ['node_modules'],
      fallback: path.join(__dirname, 'node_modules')
    },
    resolveLoader: {
      fallback: path.join(__dirname, 'node_modules')
    },
    
    • project-b requires React and ReactDOM as peerDependencies in project-b/package.json
    • project-a requires project-b as a devDependency (should also work required as a dependency) in project-a/package.json
    • local project-b is linked to project-a like so: cd project-a; npm link ../project-b

    Now when I run npm run build within project-b, the changes appear immediately in project-a

    0 讨论(0)
提交回复
热议问题