关于javascript:开发React组件-发布npm包-使用TSDX

8次阅读

共计 2100 个字符,预计需要花费 6 分钟才能阅读完成。

开发 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 example
cnpm i # yarn install
npm start # yarn start

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

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

改变一些内容

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

import * as React from 'react';
// Delete me
export 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
正文完
 0