jorgebucaran / colorette Goto Github PK
View Code? Open in Web Editor NEW๐Easily set your terminal text color & styles
License: MIT License
๐Easily set your terminal text color & styles
License: MIT License
When running tests I want to disable all the colors for whoever is using it.
But my local CLI supports colors and it will auto-detect it as such.
what I did in my tests with 1.x
import { options } from 'colorette';
describe('cli', () => {
before(() => {
// ignore colors in tests as most CIs won't support it
options.enabled = false;
});
it('outputs status along the way', async () => {
const { log } = await executeCli({ srcDir: 'fixtures/css-text' }, { captureLog: true });
expect(log[0]).to.match(/๐ Finding all file in (.*) to render.../);
});
});
e.g. I disable the colors for the function executeCli
- inside there I use import { red } from 'colorette'
.
I don't see a way how to do this with the new API? even if I do const { red } = createColors({ useColor: false })
in my test it will not effect the usage within executeCli
.
The following:
console.log(c`/`)
Renders:
//
Please consider adding support for tagged template literals. Without that feature, I'm afraid turbocolor
can't truly be considered a drop-in replacement for chalk
.
If you're upgrading from 1.x
:
createColors(options)
that returns an object with all the available color functions. Terminal support is auto-detected, override it via options.useColor
.options.enabled
has been removed in favor of createColors(options)
.isColorSupported
constant export.
true
if the terminal supports color, false
otherwise.If you were previously using options.enabled
and wish to override automatic color detection, use createColors()
.
import { createColors } from "colorette"
...
const { blue } = createColors({ useColor: myOptions.enabled })
console.log(blue("I'm blue"))
This check assumes that anything running on Windows supports colors, which is not true and results in garbage output sometimes. For example, the GitHub Desktop app doesn't support colors for its output for precommit hooks and it sets env.TERM
to dumb
. Comparing with supports-color package which handles this correctly, this check should probably have a higher priority than the platform.
Hi!
Trying to create new Vue application with vue-cli command vue create brief-vue
and then run and got an error:
Error: Package exports for '/Users/aleksandr/Documents/brief-vue/node_modules/colorette' do not define a valid '.' target
Error: Package exports for '/Users/aleksandr/Documents/brief-vue/node_modules/colorette' do not define a valid '.' target
at resolveExportsTarget (internal/modules/cjs/loader.js:545:13)
at applyExports (internal/modules/cjs/loader.js:459:14)
at resolveExports (internal/modules/cjs/loader.js:508:12)
at Function.Module._findPath (internal/modules/cjs/loader.js:577:20)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:879:27)
at Function.Module._load (internal/modules/cjs/loader.js:785:27)
at Module.require (internal/modules/cjs/loader.js:956:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/aleksandr/Documents/brief-vue/node_modules/autoprefixer/lib/autoprefixer.js:5:17)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1103:10)
at Module.load (internal/modules/cjs/loader.js:914:32)
at Function.Module._load (internal/modules/cjs/loader.js:822:14)
at Module.require (internal/modules/cjs/loader.js:956:19)
at require (internal/modules/cjs/helpers.js:74:18)
at /Users/aleksandr/Documents/brief-vue/node_modules/@vue/cli-service/lib/config/css.js:87:11
error Command failed with exit code 1.
Seems like the required file is missing: https://github.com/jorgebucaran/colorette/blob/master/package.json#L18
In my node_modules:
My setup:
macOS Catalina 10.15.6
yarn 1.22.4
node v14.8.0
@vue/cli 4.5.3
I tried to colour a message like red(true)
, but TS warned me that Color
needs to be string | number
(index.d.ts
(L2)).
I think that it should be of any
type, just like console.log()
or Logger
from @nestjs/common
can accept them.
I havenโt looked much into your code, but if you really need string | number
, you could use JSON.stringify()
on other types, however, I think it could be done without it.
I know colorette is already very small, but its architecture would allow for even smaller and more efficient output when bundling colorette if there was an ESM build that provided named exports. The current approach of putting everything on module.exports is unfortunately not suitable for tree-shaking as bundlers usually cannot tear that object apart.
If you do not want to maintain two builds, you could also do the conversion automatically with a tool like Rollup ๐
Line 92 in cfdfb4a
Due to this, calling createColors
without arguments throws an error in TypeScript
It seems like the idea of color functions export was copied from kleur
:
kleur
: lukeed/kleur@41e4696colorette
: 0226f47You should give honor to kleur
author and mention him in docs.
I wrote c.js because I wanted to explore template literals, but now I regret having incorporated this functionality into this project. I think c.js would make a little nice side project, but it's place is not in clor.
I really like a minimalism of this library, but I also have to create clickable links in terminal.
I thought maybe it is possible to add one more very useful modifier?
const { link } = require("colorette")
console.info(`App is now running on ${link('http://localhost:3000')}`)
refs:
I am running into a strange issue that started when updating tailwind/postcss packages that use colorette and running webpack via react-cypress-unit-test testing library.
The error I am getting is
Webpack Compilation Error
./app/javascript/components/Input/Input.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ./node_modules/colorette/index.js
require() of ES modules is not supported.
require() of ./node_modules/colorette/index.js from ./node_modules/postcss/lib/css-syntax-error.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from ./node_modules/colorette/package.json.
If I explicitly install colorette 1.2.0 instead of 1.2.1 everything seems to work fine.
I get error in browser: "process is not defined"
I think the reason is in Vite and its handling of environment variables.
Similar problem:
https://stackoverflow.com/questions/71083110/vue-uncaught-referenceerror-process-is-not-defined
const linkUrl = "https://www.example.com";
const linkText = "Visit Example Website";
const linkOutput = `\u001b]8;;${linkUrl}\u0007${linkText}\u001b]8;;\u0007`;
console.log(linkOutput);
In order to output linked text in the terminal, I have to do it this way. It would be great if colorette natively supported the link modifier.
Would it be possible to expose the sequences themself as something like redStart
/redEnd
or red.start
/red.end
to give users ability to set color for all the upcoming output until manually changed ?
I had a few cases where I was receiving data for output asynchronously from several child processes and wanted to colorize it by app state. It was a bit tedious to wrap each output into colorizing calls and just made code cluttered, more complicated and harder to read.
So the use case I imagine would be
const { green, yellow, grey, red } = require("colorette");
console.log(green.start)
// ... some regular state output
console.log(yellow.start)
// ... some import/sync/rebuild state output in yellow
console.log(yellow.end)
// regular output continues with green
console.log(grey.start)
// ... some cleanup state output in yellow
console.log(grey.end)
process.on('uncaughtException', function (err) {
console.log(red(err)); // errors printed out in red
})
Should Add --color and --no-color flag support
be in 2.1 (as a new feature of color auto-detection) or in 3.0 (as breaking changes of color support)?
I'm using sanitize-html in the browser which uses postcss which uses this.
When postcss imports collorette it fails on the line checking for isCompatibleTerminal
A quick fix would be to switch to the following by adding a check that tty.isatty
exists before calling it.
const isCompatibleTerminal =
tty && tty.isatty && tty.isatty(1) && env.TERM && env.TERM !== "dumb"
This would be awesome.
Turbocolor is using bright colors, not regular codes.
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
Additionally, generators for colors say,
const mauve = colorette('#b784a7')
Maybe theming too.
Recent !s
optimization was clearly backport from Nano Colors. Can you add a note that Nano Colors was an inspiration for the project.
Would be good to add a clear and a clearFill option, in order to clear/reset the screen and/or clear the screen with a bg/fg fill.
Failed to compile.
./src/index.css
Error: No valid exports main found for 'd:\myapp\node_modules\autoprefixer\node_modules\colorette'
main method is missing when running "npm run build"
This happens in file /colorette/index.cjs:6:32
Hi!
In vite HMR mode, require('tty')
returns a mock module, which is auto-defined as:
// browser-external:tty
var tty_exports = {};
__export(tty_exports, {
default: () => tty_default
});
var tty_default;
var init_tty = __esm({
"browser-external:tty"() {
init_define_process_env();
tty_default = new Proxy({}, {
get() {
throw new Error('Module "tty" has been externalized for browser compatibility and cannot be accessed in client code.');
}
});
}
});
Therefore, the check tty && tty.isatty(1)
(isCompatibleTerminal
) fails with "TypeError: tty.isatty is not a function".
I can't help by disabling via process.env.NO_COLOR
, because isCompatibleTerminal
is eagerly evaluated, no matter if NO_COLOR
is set or not.
Could you please consider:
process.env.NO_COLOR
is set.isCompatibleTerminal
only after checking for !isDisabled
.Thank you!
The implementation would be very different (ie: %c style syntax) but it would be cool to have an isomorphic api for colors in javascript consoles.
Hi. Can I have color output in one part of the app and non-color in other? Something like:
const c = colorette.instance({ enabled: opts.colors })
c.red("Error")
I have an issue when I try to run webpack with webpack.config.ts
written in typescript and ts-node
has "require": ["tsconfig-paths/register"]
// tsconfig.json
{
compilerOptions:{
paths: { /* ----------------- */ }
},
'ts-node':{
"require": ["tsconfig-paths/register"],
"compilerOptions": {
"sourceMap": false,
"module": "commonjs"
}
}
}
when I remove "require": ["tsconfig-paths/register"]
from ts-node
it runs, but webpack cannot detect aliases.
I already set module: commonjs
in my tsconfig.json
and removed type: module
from my package.json
trace
> webpack
(node:5932) Warning: require() of ES modules is not supported.
require() of /home/node_modules/colorette/index.js from /home/node_modules/webpack-cli/lib/utils/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /home/node_modules/colorette/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/node_modules/colorette/package.json.
(node:5932) UnhandledPromiseRejectionWarning: /home/node_modules/colorette/index.js:28
export const options = Object.defineProperty({}, "enabled", {
^^^^^^
SyntaxError: Unexpected token 'export'
at new Script (vm.js:84:7)
at NativeCompileCache._moduleCompile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
at Module._compile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:184:36)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (/home/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object.get colors [as colors] (/home/node_modules/webpack-cli/lib/utils/index.js:3:16)
at Object.error (/home/node_modules/webpack-cli/lib/utils/logger.js:5:58)
(node:5932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
`
Describe the bug
With Nuxt.js running on macOS with version 13.5 of Node.js $ nuxt
&& $ nuxt build
fail with error
No valid exports main found for '/Users/node_modules/colorette'
To Reproduce
Steps to reproduce the behavior:
$ nuxt
or $ nuxt build
within a Nuxt.js projectExpected behavior
Nuxtjs to build and compile successfully
My Enviornment
MacOS Catalina Version - 10.15.2
Node version - 13.5.0
Nuxt.js version - 2.13.3
We should probably support --color
and --no-color
flags in process.argv
like chalk/supports-color does.
Also: webpack/webpack-cli#2966
The preferred method of determining whether Node.js is being run within a TTY context is to check that the value of the process.stdout.isTTY property is true:
$ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat false
https://nodejs.org/api/tty.html#tty
Line 1 in 20fc196
Line 15 in 20fc196
globalThis.process?.stdout?.isTTY && env.TERM && !isDumbTerminal
This would also remove the dependency on the node:tty
module and make it "more easier" for use in the browser. i.e. NO TRANSPILATION required, you can just import ... from "./node_modules/colorette/index.js"
Colorette is coloring outside the line.
bold
and dim
use the same close code causing a bold sequence nested in a dim sequence to break the immediately following sequence (and viceversa).
const { bold, dim } = require("colorette")
console.log(bold(`Bold ${dim("Dim")} Bold`))
console.log(dim(`Dim ${bold("Bold")} Dim`))
npm install --save jorgebucaran/colorette#rgb
When try rgb colorette branch, I have this error
internal/modules/cjs/loader.js:651
throw err;
^
Error: Cannot find module '/home/dev/node_modules/colorette/test.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15)
at Function.Module._load (internal/modules/cjs/loader.js:575:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:862:12)
at internal/main/run_main_module.js:21:11
Installed with material-ui but not able to compile due to this.
I'm trying to pipe colored output through a shell pipeline in a TTY, but setting FORCE_COLOR
to a truthy value doesn't seem to work:
const { green } = require('colorette')
console.log(green('Hello, world!'))
$ FORCE_COLOR=1 node ./test.js | strings
[32mHello, world!
[39m
Hello, world!
these are vt-102 codes. ansi sequences are a partial subset. lots of the things you support don't occur in ansi
Add a test to test environment variables, e.g., FORCE_NO_COLOR
, etc.
Hey ๐
I'm trying to test console output in jest tests, but it seems colorette
doesn't work there. After looking at source code and enabled variable I found that process.stdout.isTTY
returns undefined
which results in disabled state.
I've also checked chalk and it's working in the same tests.
Maybe you have an idea how this can be fixed?
Thank you
OS: Ubuntu: 18.04
Node Version: 13.6.0
Colorette Version: 1.2.1
After the version update anytime I try to npm start
I face the following issue:
Error: No valid exports main found for './node_modules/colorette'
Am I missing something?
Thank you
Current implementation doesn't reliably determine colour support in CI environments, resulting e. g. in CI for https://github.com/pinojs/pino-pretty/tree/feat/colorette breaking.
I think these lines from supports-colour
should be included:
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
process["default"].env
is definitely incorrect. Looks like we should avoid using default imports here.
Hello, i am having problems with colorette version 1.2.1.
Require doesn't work anymore, my node version is 12.18.3 and i can't upgrade to version 14 now, i agree with the comments at this issue #50, the esm support has broken the lib support for version < 14
repro:
$ cd $(mktemp --directory)
$ npm i colorette
[ normal npm install output, installing [email protected] ]
$ node
Welcome to Node.js v13.2.0.
Type ".help" for more information.
> require('colorette')
Thrown:
Error: No valid exports main found for '/tmp/tmp.rXILKO7iaG/node_modules/colorette'
at resolveExportsTarget (internal/modules/cjs/loader.js:611:9)
at applyExports (internal/modules/cjs/loader.js:492:14)
at resolveExports (internal/modules/cjs/loader.js:541:12)
at Function.Module._findPath (internal/modules/cjs/loader.js:643:22)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:941:27)
at Function.Module._load (internal/modules/cjs/loader.js:847:27)
at Module.require (internal/modules/cjs/loader.js:1016:19)
at require (internal/modules/cjs/helpers.js:69:18) {
code: 'MODULE_NOT_FOUND'
}
>
This broke in v1.2.1, so ref #44 #45 (Doing the same but npm i colorette@<1.2.1
works as expected.)
If this is intentional, it breaks the semantic versioning promise; API break means you should increment the major version number, i.e. 2.x.x
.
Re-opening this to ensure it doesn't get overlooked. Test case copied from #41 (comment). Fixed in #41, but the patch was modified, which introduced the new bug.
In the current version (1.2.0) of Colorette, the following all have the same effect:
FORCE_COLOR=1
FORCE_COLOR=0
FORCE_COLOR=
i.e. FORCE_COLOR=<falsey/no value>
incorrectly forces color which wouldn't otherwise be displayed.
const { green } = require('colorette')
console.log(green('Hello, world!'))
$ FORCE_COLOR=1 node ./test.js | strings
[32mHello, world!
[39m
$ node ./test.js | strings
Hello, world!
$ FORCE_COLOR=0 node ./test.js | strings
[32mHello, world!
[39m
$ FORCE_COLOR= node ./test.js | strings
[32mHello, world!
[39m
If you store a style stack in a variable, e.g. const colour = tc.red.bgCyan.bold
, the first call will be styled as expected, but any further calls to it will only have the first base style. I dunno if this is by design or whatever, but thought I'd report it just in case.
const tc = require('turbocolor');
const func = tc.red.bgCyan.bold;
const first = func('foobar');
const second = func('foobar');
console.log(first, second);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.