我制作了几个简单的可重复使用的React组件,并想知道在我的package.json中正确地包含一个对React的依赖项,以便使用npm发布。
我目前正在这样做:
假设我的组件将使用最新版本的React,并且我已经测试过它可以与该版本配合使用。 例如0.13.3
"peerDependencies": {
"react": "^0.13.3"
},
我制作了几个简单的可重复使用的React组件,并想知道在我的package.json中正确地包含一个对React的依赖项,以便使用npm发布。
我目前正在这样做:
假设我的组件将使用最新版本的React,并且我已经测试过它可以与该版本配合使用。 例如0.13.3
"peerDependencies": {
"react": "^0.13.3"
},
对于可重用组件:
peerDependencies
和 devDependencies
中都要添加一个 react
依赖。dependencies
中加入 react
依赖。peerDependencies
指定您的可重用组件所支持/需要的 React 版本。使用 npm 2 时,这也会将 React 添加到要安装的模块列表中,但是在 npm 3 中不再如此。
devDependencies
确保在开发组件时运行 npm install
或在 Travis 或类似平台上运行测试时安装 React。
如果将 react
放在 dependencies
中,如果有人在自己的 package.json
中使用了不同版本的 React,则会导致安装多个版本的 React - 拥有多个版本的 React 不仅会使构建变得臃肿,还会导致不同版本试图相互交互时出错。
export default ({ React }) => {
const InjectedComponent = props => (
<p style={{color: props.color}}>This component has no React npm dependencies.</p>
)
/** other stuff */
return { InjectedComponent }
}
app.js
import React from 'react'
import { render } from 'react-dom'
/** Import the default export factory from our library */
import createInjectedComponent from 'injected'
/** Call the factory, passing its dependencies (guaranteed to match what we're bundling) and get back our component */
const { InjectedComponent } = createInjectedComponent({ React })
render(<InjectedComponent color="blue" />, document.getElementById('root'))
如果你的组件只能与特定版本的React或其他依赖项一起使用,可以在传递给React参数的版本上编写一些断言。总的来说,以这种方式构建库应该会减少因发布任何版本的React而出现新构建问题的可能性,并更重要的是确保您不会导致库消费者捆绑多个版本的React和其他大型库。这种模式与npm link非常搭配(我通常同时运行16个以上的npm链接库,并且在没有使用这种模式时遇到了问题)。你可以将react
放在peerDependencies
或dependencies
中。区别在于,使用peerDependencies
时,react
仅会为使用你的包的包安装一次。如果将其放在dependencies
中,则react
将被安装两次,一次为使用你的包的包,另一次为你的包。
React本身似乎更喜欢peerDependencies
。显然,你不希望在JavaScript捆绑包中有两个不同版本的react
(如果使用dependencies
,默认情况下会发生这种情况),但是使用npm dedupe
很容易解决这个问题。
因此,没有正确的方法,peerDependencies
和dependencies
都可以工作。使用dependencies
更符合node/NPM的方式,但是使用peerDependencies
对于不知道npm dedupe
及其必要性的你的包的用户更友好。
require('react')
?可能是因为我现在正在使用npm link
链接到我的组件,但webpack无法解析我的组件的require('react')
。 - Fiona Hopkinsnpm link
和peerDependencies
不太顺畅。似乎使用npm pack
进行本地测试并与 webpack 的require
正确配合可以解决这个问题。 - Fiona Hopkinsprop-types
怎么样?我本来以为它也应该是peerDependency
,但我看到很多例子中它是dependency
。 - dralth