網站搜尋

javascript - 發佈 npm 套件時的導出方法


我正在嘗試發布一個 npm esm 模組,該模組導出兩個方法。當模組被安裝並導入時,我希望用戶能夠像這樣導入它:

import { convertCsvToWorkbook, createFlatfile } from 'csvtoflatfile';
console.log(convertCsvToWorkbook, createFlatfile);

// or

import csvtoflatfile from 'csvtoflatfile';
console.log(csvtoflatfile)

它在我的本地示範中可以運作,但從 npm 安裝該模組時,我收到錯誤:模組 '"csvtoflatfile"' 沒有匯出成員 'convertCsvToWorkbook'.ts(2305)

這個匯入在某種程度上可以運作,但我似乎無法實際存取它的方法:


我正在這裡在我的 index.ts 中分別導出這些方法,看起來像這樣:

export const convertCsvToWorkbook = () => {}
export const createFlatfile= () => {}

export default {
    convertCsvToWorkbook,
    createFlatfile,
};

我該如何修正我的匯出,以便它們在透過 npm 下載時可以被正確匯入?

答案#1

我認為問題出在你的 "types": "./@types/index.d.ts" package.json 中的打字設定,它指向一個固定的類型檔案,而這個檔案應該是在你構建代碼時生成的。

因此,我建議移除此設置,TS 將幫助你在與你的 index 檔案 dist/index.js 相同的位置查找你的 index.d.ts

答案#2

// you are already exported as `named export` here
export const convertCsvToWorkbook = () => {}
export const createFlatfile= () => {}

// you don't to do `default export` here
export default {
    convertCsvToWorkbook,
    createFlatfile,
};