NodeJS包输出空字符串



我试图创建我自己的NodeJS包,使用粉笔输出彩色字符串,但我得到空字符串作为输出(当我在终端运行node test.js时)我尝试在线搜索,但找不到任何原因。有人知道是什么导致了这个错误吗?

index.js文件

import chalk from 'chalk';
import pkg from 'koa/lib/request';
const { charset } = pkg;
const fontColors = ['red','green','yellow','blue','magenta','cyan',];
export const colourfulLog = (string) => {
const colorString = string.split(' ')
.map(word => {
const randclrindex = Math.floor(Math.random() * fontColors.length);
const randColor = fontColors[randclrindex];
return chalk[randColor][word];
})
.join(' ');
console.log(colorString);
}

. js文件

import { colourfulLog } from './index.js';
colourfulLog(' Test the colorful log package');

包。json文件

{
"name": "colorful-log-ax",
"version": "1.0.0",
"description": "first package",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "AT",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.1"
},
"type": "module"

}

您的index.js文件中有错误:

return chalk[randColor][word];

你正在使用方括号来动态指定一个方法:chalk[randColor]就像说粉笔。randColor,然后像这样应用到word上:

return chalk[randColor](word);

最新更新