使用TypeScript + React發佈組件到Npm

最近封裝了項目中使用的React地圖組件,摸爬滾打發布到npm上;學到的知識點也比較散,如TypeScript、Commit規範/版本語義化、React組件測試、Npm發佈更新、Readme模板、組件文檔搭建等,有的知識點也是淺嘗輒止(只知其一;不知其二😱),先記錄下來,後期有時間深挖。javascript

目錄

  1. 腳手架選擇
  2. tsdx使用與配置
  3. TypeScript基礎
  4. Commit規範
  5. Npm發佈/配置/更新
  6. Readme模板
  7. React測試
  8. 組件文檔搭建

1. 腳手架選擇

發佈前看了不少教程,都是本身配置Webpack、Babel、Rollup,輔助的還有ESLint、Jest,想一想都頭大,社區有不少開箱即用的零配置腳手架,我用的tsdx,自行參考吧。css

有推薦或更好用的腳手架還請告知😘,留着下次用。html

2. tsdx使用與配置

按照文檔生成項目便可,需本身手動配置Less、ESLint,以下:vue

Less配置

安裝依賴插件java

$ yarn add rollup-plugin-postcss autoprefixer cssnano less --dev
複製代碼

tsdx.config.js配置文件修改react

const postcss = require('rollup-plugin-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      postcss({
        plugins: [
          autoprefixer(),
          cssnano({
            preset: 'default',
          }),
        ],
        inject: false,
        // only write out CSS for the first bundle (avoids pointless extra files):
        // extract: !!options.writeMeta,
        extract: 'mapLine.min.css',
      })
    );
    return config;
  },
};
複製代碼

ESLint配置

腳手架建立的項目沒有.eslintrc.js.eslintignore文件,需手動添加。git

也能夠用yarn lint --write-file生成,文檔有說明。github

.eslintrc.js文件:web

module.exports = {
  "extends": [
    "react-app",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended" // 重點
  ],
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}
複製代碼

Start 預覽

源碼在src目錄下,example目錄可預覽,須要分別在根目錄和example下安裝依賴和Start,先在根目錄Startexample Starttypescript

參考教程

3. TypeScript基礎

剛開始使用TypeScript極可能會寫出AnyScript風格的代碼,畫風以下🙋(我寫的)。

阮一峯推薦教程:TypeScript 入門教程很贊 👍。

我是先用jsx寫出功能,又遷移到TypeScript,記錄幾個經常使用的Interface定義語法。

非必選

在類型定義中,有些屬性爲非必須參數,使用?標識。

interface anime {
  show?: boolean;
  icon?: string;
  pathColor?: string;
  type?: string;
}
複製代碼

數組類型

在數組中放置對象,可以使用Array<InterfaceName>InterfaceName[]定義。

interface pathItem {
  iconText: string;
  title: string;
  theme?: number;
}

interface defaultOptions {
  path: Array<pathItem>;
  pathColor?: string;
  donePath?: pathItem[];
}
複製代碼

未知屬性、繼承

已知屬性名但不知道類型,能夠用any定義,未知屬性名已知類型可以使用[propName: string]: string;定義;爲了避免重複定義,使用extends關鍵詞繼承其餘interface

代碼:

interface pathItem extends donePathItem {
  iconText: string;
  title: string;
  [propName: string]: any;
}

interface donePathItem {
  LT: number[];
}
複製代碼

4. Commit規範

以前對Git規範不是很深刻,只有使用 git rebase合併一些無用commit信息,推薦下開源的規範文檔。

7個類別

翻看了幾個開源項目的commit和規範說明,主要是標明commit的7個類別。

- feat:新功能(feature)
- fix:修補bug
- docs:文檔(documentation)
- style: 格式(不影響代碼運行的變更)
- refactor:重構(即不是新增功能,也不是修改bug的代碼變更)
- test:增長測試
- chore:構建過程或輔助工具的變更
複製代碼

VsCode插件使用

我我的主要是在VsCode中提交Commit,推薦2個插件。

快捷生成message:git-commit-plugin

Commit記錄展現:Git History

命令行配置

在命令行中使用Git能夠使用Commitizen生成Commit message模板,並用Commitlint檢查;參見教程

5. Npm發佈/配置/更新

註冊再也不贅述,我這麼笨的人均可以搞定,聰明的你必定沒問題👩‍🎓‍,如下是細節。

打包路徑

使用yarn build打包完之後,文件生成到dist目錄,檢查package.json中的main與打包路徑一致便可。

主頁與倉庫地址

正確配置homepagerepository才能在Npm介紹中展現出來。

{
  "homepage": "http://nihaojob.gitee.io/carui/#/carui/maps",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/nihaojob/mapLine.git"
  },
}
複製代碼

發佈

國內不少小夥伴設置過npm鏡像源,記得還原爲官方,而後按照提示輸入信息就成功了,簡單吧💁 ?

$ npm config set registry https://registry.npmjs.org/
$ npm publish
複製代碼

更新

修改Readem文件後,使用如下命令更新。

官方文檔:docs.npmjs.com/about-packa…

$ npm version patch
$ npm publish
複製代碼

版本也要遵循規範,沒有來得及深挖,先留坑位🏌。

6. Readme模板

Readme應該告訴人們爲何應該使用以及如何安裝、使用。留坑優化🏌。

模板

推薦一份高Start的模板:standard-readme

也能夠使用readme-md-generator交互式的生成Readme文件。

徽標生成

shields.io可根據GitHub倉庫自動生成徽標。

CI徽標

GitHub配置的Actions成功執行,就能夠從CI頁面拷貝徽標。

阮一峯:GitHub Actions 入門教程

測試覆蓋率徽標

多種多樣的的工具和方法,我還沒學會,等我更新🏌。

7. React測試

tsdx並無自動生成jest.config.js文件,如需定義能夠手動增長,列下碰見的問題。

組件中引入less報錯

安裝依賴

$ yarn add --dev identity-obj-proxy
複製代碼

package.json配置moduleNameMapper

{
 "jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    }
  },
}
複製代碼

document is not defined

在測試文件頭部增長環境說明,例子

/**
 * @jest-environment jsdom
 */
複製代碼

引入第三方sdk

我在組件內有使用高德的全局變量,須要高德的SDK文件加載完畢後再執行測試,參考了react-amap的實現。

// PromiseScript加載
function getAmapuiPromise() {
  const script = buildScriptTag(
    'https://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Driving'
  );
  const p = new Promise(resolve => {
    script.onload = () => {
      resolve();
    };
  });
  document.body.appendChild(script);
  return p;
}
// 建立script標籤
function buildScriptTag(src: string) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.defer = true;
  script.src = src;
  return script;
}

describe('it', () => {
  it('正常渲染', () => {
    // 加載高德後執行
    getAmapuiPromise().then(() => {
      initDemo();
    });
    function initDemo() {
      const div = document.createElement('div');
      ReactDOM.render(<Maps {...options} />, div); ReactDOM.unmountComponentAtNode(div); } }); }); 複製代碼

8. 組件文檔搭建

有不少相似的工具,主要是爲了解決組件文檔的問題。

我選了dumi,緣由是文檔好看💁,dumi剛發佈不久,但使用體驗真的不錯。

官方介紹爲:是一款基於 Umi 打造、爲組件開發場景而生的文檔工具。

文檔源碼:gitee.com/nihaojob/Ca…

留坑與總結

還有不少沒有搞定的事情,須要學的也愈來愈多,爲了質量和落地,先列個ToDoList。

  • VsCode Jest debug配置
  • React Jest 補充測試用例
  • 測試覆蓋率徽標
  • Readme按照模板修改
  • 版本語義化落地
  • np工具熟悉
  • TypeScript深刻學習

才疏學淺,懇請斧正,還請Stars、點贊鼓勵💁。

GitHub項目:github.com/nihaojob/ma…

相關文章
相關標籤/搜索