Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Make an npm beautiful console logging package using ansi

  1. User

    Make an npm beautiful console logging package using ansi

  2. Assistant

    Sure! Here's an example of a simple npm package that allows you to create beautiful console logs using ANSI escape codes:

    First, create a new directory for your package and navigate to it in the terminal. Then, initialize a new npm package by running npm init and following the prompts.

    Next, create a new JavaScript file, index.js, and open it in your preferred code editor.

    Inside index.js, we will define a few utility functions to format and colorize the console logs. Here's an example implementation:

    const colorize = (message, color) => `\x1b[${color}m${message}\x1b[0m`;
    
    const log = (message, color) => {
      const formattedMessage = color ? colorize(message, color) : message;
      console.log(formattedMessage);
    };
    
    const success = (message) => log(message, '32'); // Green
    const warning = (message) => log(message, '33'); // Yellow
    const error = (message) => log(message, '31'); // Red
    

    The colorize function takes a message and a color code and wraps the message in ANSI escape codes to display it in the specified color.

    The log function is a helper function that takes a message and an optional color. If a color is provided, it uses the colorize function to format the message in that color. Otherwise, it logs the message as is.

    The success, warning, and error functions are convenience functions that call the log function with predefined colors.

    Now, in order to make this package installable and usable within other projects, we need to export these utility functions. Modify index.js as follows:

    module.exports = {
      log,
      success,
      warning,
      error,
    };
    

    Finally, you can test your package locally by creating a test file, test.js, in the same directory and using your package:

    const { log, success, warning, error } = require('./index');
    
    log('Regular console log');
    success('Success message');
    warning('Warning message');
    error('Error message');
    

    To run the test, execute node test.js in the terminal. You should see formatted and colorized console logs according to the message type.

    You can now publish your package to the npm registry by running npm publish from the root of your package. After publishing, other users can install and use your package in their projects by running npm install your-package-name.