1.创建react项目
npm create vite@latest vite-react-packages-to-npm
2.yarn add vite-plugin-libcss
(为了在打包后主动加上css样式)
3.创建一个要封装的组件 packages 里面创建一个需要封装的组件内容,例如packages / Button/ Button.tsx
import "./index.scss";
import React, { PropsWithChildren } from "react";
export type ButtonProps = {
className?: string;
};
const Button: React.FC<PropsWithChildren<ButtonProps>> = ({ ...props }) => {
return <button className="btn" {...props} />;
};
export default Button;
###4. packages 下创建一个到处文件packages / index.ts
export { default as Button } from "./Button/Button";
export type { ButtonProps } from "./Button/Button";
###5.修改package要发布的路径
"name": "my-packages-name", //包名
"private": false, //true 会报错
"version": "0.0.9",//当前版本
"type": "module",
"files": [
"lib"
],
"main": "./lib/nancy-react-plungin.umd.cjs",//打包后的地址
"module": "./lib/nancy-react-plungin.js",
"typings": "./lib/index.d.ts",
"exports": {
".": {
"import": "./lib/nancy-react-plungin.js",
"require": "./lib/nancy-react-plungin.umd.cjs"
}
},
6. npm login 会弹出登录
7.npm publish 发布组件到npm
8.测试是否可以 yarn add my-packages-name
import "./App.css";
// import Button from "../packages/Button/Button.tsx";
import { Button } from "my-packages-name";
function App() {
return (
<div>
<Button>click</Button>
</div>
);
}
export default App;
需要代码请留言