npm 发布react组件

256 阅读1分钟

注册账号请去官网 www.npmjs.com

1、登录npm

在命令行执行

npm login  //登录
npm logout //  注销

 输入账号 密码 邮箱

 把下面步骤完成后执行下面命令 成功后 自己的可以尝试在npm添加自己的组件了

npm publish //发布

踩过的坑

403邮箱验证

404没有登录成功

2、ts项目搭建

1) npx create-react-app my-app --typescript:该方法已经很不在使用
2) npx create-react-app my-app --template typescript:新建一个使用ts的React项目 
3) 修改入口文件index.tsx 

import App from './App';
export default App;

  4) 去掉组件中的css文件 (css单独打包见下文)

3、打包文件

  1)添加npm打包文件 build.json

{  "compilerOptions": {    "outDir": "dist",    "module": "esnext",    "target": "es5",    "declaration": true,    "jsx": "react",    "moduleResolution":"Node",    "allowSyntheticDefaultImports": true  },  "include": [    "src"  ],  "exclude": [    "src/**/*.test.tsx",    "src/**/*.stories.tsx",    "src/setupTests.ts"  ]}

  2)  修改package.json文件 "private": false, 是必须修改的

  "private": false,  "main": "dist/index.js",  "module": "dist/index.js",  "types": "dist/index.d.ts",

  3)dist是生成的包跟目录 请打包后注意改文件

  4) 配置打包命令 build-npm 

"scripts": {    "start": "react-scripts start",    "build": "react-scripts build",    "build-npm": "tsc -p build.json",     "test": "react-scripts test",    "eject": "react-scripts eject"  },

"build-css": "node-sass ./src/styles/index.scss ./dist/index.css", //css打包命令

  5) 给自己的包起一个高大上的名字把

"name": "ray-test","version": "0.1.0","description": "这是Ray的第一个正式的测试项目",

4、添加一个可视化的工具

www.jianshu.com/p/409b7eed5… 推荐使用