创立文件夹

cheney-react-library

进入文件夹

yarn init -y

装置要害包

yarn add rollup rollup-plugin-babel @babel/core @babel/preset-env @babel/preset-react -D

我的项目根目录创立 src/index.jssrc/Components/Switch.jslib

我的项目根目录创立 .gitignore 来进行 git疏忽 治理

node_modules

咱们用 yarn 来公布包,须要在我的项目根目录创立 .yarnignore 来进行 yarn疏忽 治理

src.gitignore

我的项目根目录创立 .babelrc 来进行 babel 配置

{ "presets": ["@babel/preset-env", "@babel/preset-react"]}

我的项目根目录创立 rollup.config.js 来进行 rollup 配置

import babel from 'rollup-plugin-babel'export default { input: './src/index.js', output: { file: './lib/index.js', format: 'cjs' }, plugins: [babel()]}

src/Components/Switch.js 中写入

import React from 'react'export default function Switch() { return ( <h1>Switch</h1> )}

src/index.js 中写入

// import Switch from './Components/Switch'// export { Switch }// 两种写法export { default as Switch } from './Components/Switch'

至此我的项目目录为

运行 yarn run rollup -c 进行打包,打包胜利

然而发现有个正告

(!) Unresolved dependencieshttps://rollupjs.org/guide/en/#warning-treating-module-as-external-dependencyreact (imported by src/Components/Switch.js)

意思是 react 是内部依赖,咱们须要在 rollup.config.js 中把 react 设为一个内部依赖,防止每次打包进去

import babel from 'rollup-plugin-babel'export default { ... external: ['react']}

运行 yarn run rollup -c 进行打包,打包胜利,且没有正告

咱们在 package.json 中整顿一下命令

当前咱们执行 yarn buildyarn start 就能够了,省得写一长串的命令

yarn run rollup -c -w-w 是监控作用,咱们改变代码,会天然响应更新

如果想本地调试,根目录运行 yarn link 本地注册包,那么在其余我的项目根目录中运行 yarn link cheney-react-library 就能够链接咱们的组件了,如果不想链接,运行 yarn unlink cheney-react-library 即可

如果想把包公布到 npm ,须要查看根目录下有无 README.md ,没有的话须要增加一些货色

还需查看 package.json 中的 main 是否为 lib/bundle.js ,以及增加 authordescriptionkeywords

description 就是包形容

查看 npm 镜像地址是否正确,不正确须要切换过去

npm config get registry

而后运行 yarn publish ,输出个人信息就会看到一步步地公布胜利

如果第三步呈现错误信息像

error Couldn't publish package:"...: You do not have permission to publish "...". Are you logged in as the correct user?" 意味着咱们的包名和仓库中的已存在包名反复了,须要批改包名。能够通过 yarn info 包名 来查看仓库是否存在此包

公布胜利后在 npm 仓库中能够搜寻到本人的包

如果想撤销本人公布的包,运行

npm unpublish 包名 --force

或者撤销某一版本

npm unpublish 包名@version