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

前端 未结 9 1657
无人共我
无人共我 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条回答
  •  猫巷女王i
    2020-12-28 14:40

    Someone clevererer than I (@mojodna) came up with this solution: remove the duplicate dependencies from the external component, and resolve them with your project's copies of those deps.

    Step 1: Remove the dependencies from your external component's node_modules

    As @cleong noted, you can't just remove the deps from the external component's node_modules, because your project's build step will fail when it hits the now-missing dependencies in the external component.

    Step 2: Add your project's node_modules to NODE_PATH

    To fix this, you can append the project's node_modules to the NODE_PATH environment variable when running your build step. Something like e.g. this:

    NODE_PATH=$(pwd)/node_modules/ npm start

    (where npm start is your script that bundles your external component, via e.g. Browserify, Webpack, etc.)

    In fact, you could always append that NODE_PATH addition to your build scripts, and it would work whether or not you've npm linked anything. (Makes me wonder if it shouldn't be default npm behavior...)

    Note: I left my existing answer because there's some conversation there, and this is a different (and better) solution.

提交回复
热议问题