如何把js函數發布成npm並支持typescript


文章原文: https://www.cnblogs.com/yalong/p/15214644.html

代碼倉庫地址: https://github.com/YalongYan/downlaod-table-to-csv

===== start 2021-12-01新增

用typescript實現自己的js函數庫 , 請看這里: https://www.cnblogs.com/yalong/p/15627449.html

===== end 2021-12-01新增

對於一些常用的js函數, 可以發布到npm上,方便使用,特此記錄下過程
本次npm封裝的函數是基於 ES6 模塊規范,並且支持 typescript

整個過程如下:

一. npm init 創建項目

執行 npm init
然后根據提示輸入相應的配置,最終生成 package.json
下面就是我執行的過程,比如 git repository 如果沒有的話直接回車跳過就行

admin@admindeMacBook-Pro tableToCsv % npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (tabletocsv) table-to-csv
version: (1.0.0) 0.0.1
description: 把table數據轉成csv格式並下載
entry point: (index.js) 
test command: 
git repository: 
keywords: table-download csv
author: yyl
license: (ISC) 
About to write to /Users/admin/yanyalong/npm/tableToCsv/package.json:

{
  "name": "table-to-csv",
  "version": "0.0.1",
  "description": "把table數據轉成csv格式並下載",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "table-download",
    "csv"
  ],
  "author": "yyl",
  "license": "ISC"
}


Is this OK? (yes) yes
admin@admindeMacBook-Pro tableToCsv % 

最終生成的 package.json 如下:

{
  "name": "table-to-csv",
  "version": "0.0.1",
  "description": "把table數據轉成csv格式並下載",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "table-download",
    "csv"
  ],
  "author": "yyl",
  "license": "ISC"
}

二.新建index.js文件

在package.json 同級目錄下新建 index.js,存放要發布到npm上的函數 該文件內容如下

/**
 * 導出支持空數據, 支持空格
 * @param { Array } initColumns - 列的數據
 * @param { Array } initList - 表格的數據
 * @param { string } name - 下載文件的名字(不用帶.csv)
 */
const TableToCsv = (initColumns, initList, name = '表格') => {
  let str = '';
  let arr = [];
  let keyArr = [];
  initColumns.forEach((item) => {
    arr.push(item['title']);
    keyArr.push(item['key'] || item['dataIndex']);
  });
  str = arr.join(',') + '\n';
  for (let i = 0; i < initList.length; i++) {
    let subArr = keyArr.map((item) => {
      let temp = initList[i][item] === undefined ? '' : initList[i][item] + ''; // 轉成字符串
      // 下面解決中文亂碼問題 會把空格轉成 #, 這里把空格轉成 \xa0 就不會有這個問題了
      return temp ? temp.replaceAll(/\s+/g, '\xa0') : '';
    });
    let subStr = subArr.join('\t,');
    subStr += '\n';
    str += subStr;
  }
  // \ufeff 解決中文亂碼問題
  var blob = new Blob(['\ufeff', str], { type: 'text/plain' });
  let object_url = window.URL.createObjectURL(blob);
  let link = document.createElement('a');
  link.href = object_url;
  link.download = `${name}.csv`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export default TableToCsv;

這里就以TableToCsv函數為例, TableToCsv是把table表格的數據轉為csv格式並下載

三.創建typescript定義文件

為了讓該npm包支持typescript, 所以需要創建一個 index.d.ts文件

為了演示,參數的 type類型 以 any 定義了,內容如下

declare const TableToCsv: (initColumns: any[], initList: any[], name: string) => void;
export default TableToCsv;

四.完善 package.json

package.json 中還需要添加幾個字段

  • private - 要發布到npm上, private 必須設置成false
  • main - 該npm包的入口文件
  • module - ES6模塊規范的入口文件
  • types - typescript 定義文

關於為什么要加 module字段,主要是是為了用戶在使用我們的包時可以享受 Tree Shaking 帶來的好處

package.json中 module 字段更多解釋可以看這里:聊聊 package.json 文件中的 module 字段

完善后的 package.json 如下:

{
  "name": "table-to-csv",
  "version": "0.0.6",
  "description": "把table表格下載為csv格式的文件",
  "author": "yyl",
  "private": false,
  "main": "index.js",
  "module": "index.js",
  "types": "index.d.ts",
  "license": "MIT",
  "keywords": [
    "table-download",
    "csv"
  ]
}

五.添加readme

一個好的npm包肯定得有readme說明文件的,里面包含該npm包怎么使用,以及一些注意事項等
readme 內容如下:

安裝
npm i table-to-csv -S

使用示例

import TableToCsv from 'table-to-csv';
const initColumns = [
  {
    dataIndex: "Index",
    key: "Index",
    title: "序號",
  },
  {
    dataIndex: "userid",
    key: "userid",
    title: "用戶Uid",
  },
  {
    dataIndex: "score",
    key: "score",
    title: "收益點",
  }
 ]
 const initList = [
    {
      id: '32',
      Index: 1,
      userid: '11',
      score: '10'
    },
    {
      id: '42'
      Index: 2,
      userid: '22',
      score: '20'
    },
    {
      id: '89',
      Index: 3,
      userid: '33',
      score: '30'
    }
  ];

 TableToCsv(initColumns, initList, '統計表格')
 
 說明:
 initColumns 里面key 和 dataIndex 必須有一個

六.發布到npm

  1. 前提得有個npm賬號,沒有的去 https://www.npmjs.com/ 注冊一個
  2. npm login 登錄
  3. npm whoami 查看當前登錄用戶
  4. npm publish 發布到npm
  5. 記得每次發版的時候 版本號不能跟之前的一樣,不然發布不上去

七.項目中使用

我的項目是react + ts 環境

實際使用效果截圖如下:

可以看到ts的檢驗都是有效的

總結

1.優點:可以把項目中的代碼直接復制過來,就可以發布到npm
2.缺點:由於是 ES6 的代碼,使用的時候,安裝到 node_modules 下了, 如果webpack配置忽略了 node_modules 目錄,會導致沒有處理該npm包里面的代碼,對於不支持ES6 的瀏覽器可能會報錯了,解決方法有兩種

  • 一種就是不要 exclude 相當於對於node_module下的代碼也進行編譯了,犧牲了打包時間
  • 一種是使用include 包含該函數組件 include: [/node_modules\/table-to-csv/, /src/], 這樣就可以

代碼倉庫地址: https://github.com/YalongYan/downlaod-table-to-csv


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM