1

So I am building an Angular CLI 6 application and I wanted to implement the Chalk package to have some styling in my console logs.

For testing purposes, I've imported Chalk in my app.component.TS file as follows:

import { component } from '@angular/core';
import * as chalk_ from 'chalk';

 @Component({
    //not important 
 })

export class AppComponent {
title = 'My App';

constructor() {
  console.log(chalk.blue('Hello'));
}

chalk.blue gives me the error: Property blue does not exist. When I change that into chalk.default.blue it works and VS code gives me no errors.

When I check the console in the browser I get the error: index.js:8 Uncaught ReferenceError: process is not defined.

Can someone help me out with this? I have also tried Colors and I've noticed that all these packages require you to use require() to implement them. But this is ES5 style...

const chalk = require('chalk');

or

var colors = require('colors/safe');
Mirwais
  • 131
  • 1
  • 4
  • 18
  • 1
    Angular applications execute in the browser. Not in your shell. The console is the browser console, not your terminal. The browser executes the code, not NodeJS. – JB Nizet Jun 19 '18 at 20:11
  • You try declaring chalk variable? eg `declare const chalk: any;` Otherwise i don't see where you declare or otherwise get the "chalk" you're calling the `blue` method against. – Roddy of the Frozen Peas Jun 19 '18 at 20:53
  • @RoddyoftheFrozenPeas I am just following the instructions as given here: https://github.com/chalk/chalk << Instead of "const chalk = require('chalk');" I am doing the import as it differs from es5 – Mirwais Jun 19 '18 at 21:29

3 Answers3

4

the above answers are correct, but here is how to get colors in the chrome console

console.log('%c this is colored', 'color: green; background: red;');

Lukas Sorensen
  • 397
  • 2
  • 12
  • I did not downvote you and what you wrote might be working, but I want to use the chalk js package to do this. I am wondering why my implementation of chalk is not working. – Mirwais Jun 19 '18 at 21:32
  • 1
    this is the only way to get colors in the browser console that I know of, the other answers are correct chalk only works on nodejs (server-side) – Lukas Sorensen Jun 19 '18 at 21:39
0

The problem is that chalk is for server-side javascript not web/browser(according to process error). You probably need to find another package with similar functionality but for web.

Buczkowski
  • 2,296
  • 12
  • 18
0

This doesn't have anything to do with ES5/CommonJS or ES6+ style, e.g. require or import. Chalk doesn't implement browser support, thus it won't work in Angular or any front-end script code. Chalk 2 even requires Node.js 4 or later.

As mentioned, you have to use %c directive to style your console output in the browser.

See: https://developer.mozilla.org/en-US/docs/Web/API/console#Styling_console_output

Glenn Mohammad
  • 3,871
  • 4
  • 36
  • 45