开发React组件 公布npm包 (应用TSDX)

运行该命令,会新建组件开发的文件夹。(mylib就是我的项目名)

因为我这边的网速很烂 所以能够先装置
cnpm i tsdx@latest -g

而后在执行

npx tsdx create mylib

中途咱们会被要求抉择一个模版:

模版形容
basic用于一个TypeScript包,能够开发任何货色,灵便度高
react用于开发React组件的包,内置了@types,而且有一个基于Parcel的调试模块,帮忙疾速开发
react-with-storybook与react模版雷同,然而多内置了storybook

咱们抉择第二个,react模版。

mylib文件夹下,src文件夹是让你写源码的,example是让你开发调试用的文件夹,外面也是源码(应用你npm包的源码),dist是你编译后的输入目录,在npm pub时就会把dist上传到npm上

到这一步 从NPM下载依赖 因为我的网还是很烂,始终装不上,所以ctrl+c 退出了,应用cnpm来装置
cnpm i @size-limit/preset-small-lib @types/react @types/react-dom husky react react-dom size-limit tsdx tslib typescript --save-dev

装置实现后 目录构造是

这是想要启动它 须要关上2个shell(一个用于实时编译到dist,另一个用于example的调试)

用于实时编译的shell:

npm start # or yarn start

用于实时调试的shell:

cd examplecnpm i # yarn installnpm start # yarn start

前者会实时监测代码变更,编译最新的版本到dist中,后者会监测dist变更,将example中的内容启动,默认在 http://localhost:1234/ 运行example我的项目。

当初你能够去试着写一些内容,看看有没有失效????

改变一些内容

src/index.tsx中,默认有如下内容:

import * as React from 'react';// Delete meexport const Thing = () => { return <div>啊哈哈哈哈</div>;};

留神,src/index.tsx中export的内容,就是咱们的npm包要导出的内容。例如下面代码,导出了Thing,如果npm包名字是my-demo,未来公布后,须要这样引入:

import { Thing } from 'my-demo';

接下来,看看example/index.tsx的内容:

import 'react-app-polyfill/ie11';import * as React from 'react';import * as ReactDOM from 'react-dom';import { Thing } from '../.';const App = () => { return (     <div>        <Thing />     </div> );};ReactDOM.render(<App />, document.getElementById('root'));

本地测试时,咱们必定不能先公布再去测试,TSDX的做法比拟好,它是这么做的:

import { Thing } from '../.'; // 就是example/index.tsx的第4行

意思是去example文件夹的上一层来导入,它会发现下层文件夹的package.json,依据外面的modulemain来import到相应的内容(这些都不须要咱们关怀,因为它曾经定义好了"module": "dist/mylib.esm.js","main": "dist/index.js")。

所以,在example/index.tsx中,咱们写一些应用咱们npm包的案例,不仅不便开发时的测试,也能够作为咱们npm包的“最佳实际”,两全其美。

此外,能够关注一下example/index.html,应用example测试时,TSDX实际上是基于parcel的,会基于index.html生成网页,展现example/index.tsx中的案例。如果你须要批改html中的内容,你能够间接批改,也是十分不便的!上面是example/index.html默认的代码:

    <!DOCTYPE html>    <html lang="en">     <head>     <meta charset="UTF-8" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <meta http-equiv="X-UA-Compatible" content="ie=edge" />     <title>Playground</title>     </head>         <body>     <div id="root"></div>     <script src="./index.tsx"></script>     </body>    </html>

接下来就能够公布啦

# 公布前要先在根目录下编译 npm build # yarn build# 正式公布npm publish