react 组件封装原则_如何基于antd封装自己的react组件并发布到npm

引言

在前端项目开发过程中,有大量重复的内容,比如布局相似的模块,较多的功能表单等,我们可以提炼成组件来提升效率,减少重复建设。文章以实际工作中的项目为例,介绍如何将项目中常用的组件进行封装并发布到npm中。

1 前提要求

在开始前你需要具备以下条件:安装了Node & npm

安装了Git

基本掌握npm ,git使用方法

熟练使用 JavaScript & ES6 & CSS

基本掌握React

熟悉React ,antd

2 开始

2.1 配置git和npm

本次将我的组件库命名为nsc-components

首先配置git ,在github上创建一个新的远程仓库nsc-components,在本地运行git clone 命令,将nsc-components克隆到本地

$ git clone https://github.com/你的账户名/nsc-components

配置 npm,运行npm login,登录你的npm账号。然后运行npm init 初始化生成一个新的package.json文件.

$ npm init

name: (nsc-components)

version: (1.0.0) 0.1.0

description: an example component library with React!

entry point: (index.js)

test command:

git repository:

keywords:

Author:

license: (ISC)

About to write to /Users/alanbsmith/personal-projects/trash/package.json:

{

"name": "nsc-components",

"version": "0.1.0",

"description": "an example component library with React!",

"main": "dist/index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": ,

"license": "ISC"

}

Is this ok? (yes)

在根目录下添加以下配置文件

touch .babelrc .eslintrc .gitignore .npmignore README.md.babelrc包含编译阶段一些有用的转转码规则(presets)

.eslintrc包含linter配置

.gitignore和.npmignore分别用于忽略来自 git 和 npm 的文件

README.md也非常重要。这是我们和开源社区交流的主要方式

.babelrc

{

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

"plugins": [

"@babel/plugin-proposal-class-properties",

"@babel/plugin-proposal-object-rest-spread",

["import", {"libraryName": "antd", "libraryDirectory": "lib", "style":"css"

}],

]

}

注:这里踩了很多坑

加入["import", {"libraryName": "antd", "libraryDirectory": "li

你可能感兴趣的:(react,组件封装原则)