如何在SvelteKit浏览器环境中使用Node.js模块?
解决SvelteKit中使用number-to-words库的问题
方案1:默认导入后解构
这个库是CommonJS格式,未提供ES模块的具名导出,因此直接用import { toOrdinalWord }会失败。可以先默认导入整个模块对象,再解构需要的方法:
import numberToWords from 'number-to-words'; const { toOrdinalWord } = numberToWords; // 调用示例 console.log(toOrdinalWord(5)); // 输出 "fifth"
方案2:动态导入(适合按需加载场景)
如果默认导入仍有问题,可在组件中使用动态导入,确保在客户端环境加载模块:
<script> let result = ''; async function convertNumber(num) { const module = await import('number-to-words'); result = module.toOrdinalWord(num); } </script> <button on:click={() => convertNumber(23)}>转成序数词</button> <p>结果:{result}</p>
方案3:直接提取所需代码(最轻量化)
由于这个库逻辑简单,没必要引入完整依赖。可以直接把toOrdinalWord相关代码复制到自己的工具文件中:
- 在
src/lib/utils/下创建numberUtils.js:
function toOrdinalWord(number) { const words = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ]; const tensWords = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; function convertLessThanOneHundred(num) { if (num < 20) return words[num]; const ten = Math.floor(num / 10); const remainder = num % 10; return remainder ? `${tensWords[ten]}-${words[remainder]}` : tensWords[ten]; } function convertLessThanOneThousand(num) { const hundred = Math.floor(num / 100); const remainder = num % 100; let res = ''; if (hundred) res += `${words[hundred]} hundred`; if (remainder) res += (res ? ' ' : '') + convertLessThanOneHundred(remainder); return res || words[0]; } const specialSuffixes = { 1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', 8: 'eighth', 9: 'ninth', 12: 'twelfth' }; if (specialSuffixes[number]) return specialSuffixes[number]; const lastTwoDigits = number % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 13) { return `${convertLessThanOneThousand(number)}th`; } const lastDigit = number % 10; const suffix = lastDigit === 1 ? 'st' : lastDigit === 2 ? 'nd' : lastDigit === 3 ? 'rd' : 'th'; return `${convertLessThanOneThousand(number)}${suffix}`; } export { toOrdinalWord };
- 在组件中导入使用:
import { toOrdinalWord } from '$lib/utils/numberUtils'; console.log(toOrdinalWord(42)); // 输出 "forty-second"
内容的提问来源于stack exchange,提问作者artemetra
相关产品推荐
相关产品推荐

