Code Monkey home page Code Monkey logo

consola's Introduction

🐨 Consola

Elegant Console Wrapper

npm version npm downloads bundle

Why Consola?

👌  Easy to use
💅  Fancy output with fallback for minimal environments
🔌  Pluggable reporters
💻  Consistent command line interface (CLI) experience
🏷  Tag support
🚏  Redirect console and stdout/stderr to consola and easily restore redirect.
🌐  Browser support
⏯  Pause/Resume support
👻  Mocking support
👮‍♂️  Spam prevention by throttling logs
❯  Interactive prompt support powered by clack

Installation

Using npm:

npm i consola

Using yarn:

yarn add consola

Using pnpm:

pnpm i consola

Getting Started

// ESM
import { consola, createConsola } from "consola";

// CommonJS
const { consola, createConsola } = require("consola");

consola.info("Using consola 3.0.0");
consola.start("Building project...");
consola.warn("A new version of consola is available: 3.0.1");
consola.success("Project built!");
consola.error(new Error("This is an example error. Everything is fine!"));
consola.box("I am a simple box");
await consola.prompt("Deploy to the production?", {
  type: "confirm",
});

Will display in the terminal:

consola-screenshot

You can use smaller core builds without fancy reporter to save 80% of the bundle size:

import { consola, createConsola } from "consola/basic";
import { consola, createConsola } from "consola/browser";
import { createConsola } from "consola/core";

Consola Methods

<type>(logObject) <type>(args...)

Log to all reporters.

Example: consola.info('Message')

await prompt(message, { type })

Show an input prompt. Type can either of text, confirm, select or multiselect.

See examples/prompt.ts for usage examples.

addReporter(reporter)

  • Aliases: add

Register a custom reporter instance.

removeReporter(reporter?)

  • Aliases: remove, clear

Remove a registered reporter.

If no arguments are passed all reporters will be removed.

setReporters(reporter|reporter[])

Replace all reporters.

create(options)

Create a new Consola instance and inherit all parent options for defaults.

withDefaults(defaults)

Create a new Consola instance with provided defaults

withTag(tag)

  • Aliases: withScope

Create a new Consola instance with that tag.

wrapConsole() restoreConsole()

Globally redirect all console.log, etc calls to consola handlers.

wrapStd() restoreStd()

Globally redirect all stdout/stderr outputs to consola.

wrapAll() restoreAll()

Wrap both, std and console.

console uses std in the underlying so calling wrapStd redirects console too. Benefit of this function is that things like console.info will be correctly redirected to the corresponding type.

pauseLogs() resumeLogs()

  • Aliases: pause/resume

Globally pause and resume logs.

Consola will enqueue all logs when paused and then sends them to the reported when resumed.

mockTypes

  • Aliases: mock

Mock all types. Useful for using with tests.

The first argument passed to mockTypes should be a callback function accepting (typeName, type) and returning the mocked value:

consola.mockTypes((typeName, type) => jest.fn());

Please note that with the example above, everything is mocked independently for each type. If you need one mocked fn create it outside:

const fn = jest.fn();
consola.mockTypes(() => fn);

If callback function returns a falsy value, that type won't be mocked.

For example if you just need to mock consola.fatal:

consola.mockTypes((typeName) => typeName === "fatal" && jest.fn());

NOTE: Any instance of consola that inherits the mocked instance, will apply provided callback again. This way, mocking works for withTag scoped loggers without need to extra efforts.

Custom Reporters

Consola ships with 3 built-in reporters out of the box. A fancy colored reporter by default and fallsback to a basic reporter if running in a testing or CI environment detected using unjs/std-env and a basic browser reporter.

You can create a new reporter object that implements { log(logObject): () => { } } interface.

Example: Simple JSON reporter

import { createConsola } from "consola";

const consola = createConsola({
  reporters: [
    {
      log: (logObj) => {
        console.log(JSON.stringify(logObj));
      },
    },
  ],
});

// Prints {"date":"2023-04-18T12:43:38.693Z","args":["foo bar"],"type":"log","level":2,"tag":""}
consola.log("foo bar");

Log Level

Consola only shows logs with configured log level or below. (Default is 3)

Available log levels:

  • 0: Fatal and Error
  • 1: Warnings
  • 2: Normal logs
  • 3: Informational logs, success, fail, ready, start, ...
  • 4: Debug logs
  • 5: Trace logs
  • -999: Silent
  • +999: Verbose logs

You can set the log level by either:

  • Passing level option to createConsola
  • Setting consola.level on instance
  • Using the CONSOLA_LEVEL environment variable (not supported for browser and core builds).

Log Types

Log types are exposed as consola.[type](...) and each is a preset of styles and log level.

A list of all available built-in types is available here.

Creating a new instance

Consola has a global instance and is recommended to use everywhere. In case more control is needed, create a new instance.

import { createConsola } from "consola";

const logger = createConsola({
  // level: 4,
  // fancy: true | false
  // formatOptions: {
  //     columns: 80,
  //     colors: false,
  //     compact: false,
  //     date: false,
  // },
});

Integrations

With jest or vitest

describe("your-consola-mock-test", () => {
  beforeAll(() => {
    // Redirect std and console to consola too
    // Calling this once is sufficient
    consola.wrapAll();
  });

  beforeEach(() => {
    // Re-mock consola before each test call to remove
    // calls from before
    consola.mockTypes(() => jest.fn());
  });

  test("your test", async () => {
    // Some code here

    // Let's retrieve all messages of `consola.log`
    // Get the mock and map all calls to their first argument
    const consolaMessages = consola.log.mock.calls.map((c) => c[0]);
    expect(consolaMessages).toContain("your message");
  });
});

With jsdom

{
  virtualConsole: new jsdom.VirtualConsole().sendTo(consola);
}

Console Utils

// ESM
import {
  stripAnsi,
  centerAlign,
  rightAlign,
  leftAlign,
  align,
  box,
  colors,
  getColor,
  colorize,
} from "consola/utils";

// CommonJS
const { stripAnsi } = require("consola/utils");

License

MIT

consola's People

Contributors

akryum avatar alberto avatar antfu avatar atinux avatar barbapapazes avatar clarkdo avatar cpreston321 avatar d34thwings avatar damianglowala avatar develohpanda avatar i62navpm avatar jsonleex avatar klaseca avatar maazadeeb avatar mannil avatar mp3 avatar msokk avatar nicopennec avatar nozomuikuta avatar papb avatar pi0 avatar pimlie avatar regevbr avatar renovate[bot] avatar shingangan avatar thomaskoscheck avatar tjeeay avatar trygveaa avatar with-heart avatar xjccc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

consola's Issues

Improve documentation of addReporter and setReporter

I believe there's no examples of addReporter in the docs, and in general the logging mechanism could be explained a little more.
I created a consola Nuxt plugin, set the reporter to be FancyReporter, and then went on to use $consola.debug in my code. All worked as expected. Later, I set some $consola.error()s and the output was plaintext. I had to explicitely set the Reporter to JSONReporter above the $consola.error() calls to get them to log JSON.

Export dist for src/index.js

What problem does this feature solve?

Previous versions of consola exported all the internals which I used to create my own Consola instance in nuxt-generate-cluster: https://github.com/nuxt-community/nuxt-generate-cluster/blob/master/lib/utils/consola.js

Currently it seems the only export that is distributed is the consola instance. Which also means that the README is probably not correct. Eg when I log consola.JSONReporter it logs undefined (referring to this: https://github.com/nuxt/consola#creating-a-new-instance)

What does the proposed changes look like?

I'd also be happy with a third build file, eg so I have to import eg consola/dist/Consola to get access to all the exports in https://github.com/nuxt/consola/blob/master/src/index.js

Not sure what the best name for such an export would be

This feature request is available on Nuxt community (#c46)

Wrapped errors wrongly apply formatting

Using using wrap* helpers, we implicitly assume first argument as consola logObj format which might end with formatting errors. (nuxt/nuxt#8741)

Reproduction

const consola = require('consola')

const error = new Error('boom')
const errorObj = {
  date: new Date().toISOString(),
  level: 'error',
  message: error.message,
  error: { stack: error.stack, message: error.message }
}

console.log(errorObj)
consola.wrapAll()
console.log(errorObj)

Workarounds

  1. Use different field name than message, error
  2. console.log(JSON.stringify(errorObj, null, 2))
  3. console.log('', errorObj)
  4. consola.restoreAll()

loginWith promise result is undefined

Version

v4.1.0

Reproduction link

https://nuxt-auth.herokuapp.com/

Steps to reproduce

The following code logs undefined:

        return this.$auth.loginWith('local', {
                data: {
                    username: this.username,
                    password: this.password
                }
            }).then(response => {
                console.log(response);
            }

What is expected ?

Getting the full response

What is actually happening?

Response is undefined

EDIT: This is for the AUTH project, not consola. Is it possible to move this? I have not found out how.

This bug report is available on Nuxt.js community (#c6)

[typescript] const consola = require('consola') type is wrong

Ref: #80

Fix a typing issue that causes this to throw a typing error on consola.green:

// @ts-check

const consola = require('consola')

consola.green('foo')

Workaround:

// globals.d.ts

import { Consola } from 'consola'

declare module 'consola' {
  export = new Consola()
}
This question is available on Nuxt community (#c68)

withScope is not a function : withScope chaining

I m quite confused : sometimes it works and other it does not ! i guess it depends on context (import or require)

import consola from 'consola'
const logger = consola.withScope('scope') // is Ok

const newlogger = console.withScope('other') // is not Ok (withScope is not a function)

But it worked in some other situations i coded

I guess it comes from /node-modules/consola/dist/console.cjs.js
I have the feeling prototypes are missing in the new consola created by withScope/withDefaults: logger is just an object and no longer a Consola.

var Consola =
/*#__PURE__*/
function () {
  function Consola() {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck(this, Consola);

    this.reporters = options.reporters || [];
    this.types = Object.assign({}, types, options.types);
    this.level = options.level != null ? options.level : 3;
    Object.assign(this, this.withDefaults());
  }

  _createClass(Consola, [{
    key: "withDefaults",
    value: function withDefaults(defaults) {
      var logger = {};

      for (var type in this.types) {
        logger[type] = this._createLogFn(Object.assign({
          type: type
        }, this.types[type], defaults));
      }

      return logger;
    }
  }

Typescript definitions use reserved export keyword

ERROR  ERROR in ./node_modules/consola/types/consola.d.ts(98,1):                                                          nuxt:typescript 11:30:28
98:1 An export assignment cannot be used in a module with other exported elements.
    96 | export default consolaGlobalInstance
    97 | 
  > 98 | export = consolaGlobalInstance
       | ^
    99 | 

ℹ Version: typescript 3.7.4                                                                                                                                nuxt:typescript 11:30:28
ℹ Time: 15081ms                                                                                                                                            nuxt:typescript 11:30:28
ℹ Waiting for file changes                                                                                                                                                 11:30:28
ℹ Memory usage: 638 MB (RSS: 1.23 GB)    
This question is available on Nuxt community (#c63)

Missing types

Version

v2.1.0

Description

There are missing types for the following functions:

  • create
  • setReporters
  • withTag
  • withScope
  • wrapAll
  • restoreAll
  • wrapConsole
  • restoreConsole
  • wrapStd
  • restoreStd
  • pauseLogs
  • resumeLogs
  • mockTypes
This bug report is available on Nuxt community (#c43)

Problem error log color invisible

With my iterm configuration, I have this problem:
capture d ecran 2018-05-03 a 11 01 05

Error's details exist. If I select details, you can see this:
capture d ecran 2018-05-03 a 11 01 19

An idea for custom color ? Or other idea who can help me.

Thank you

This question is available on Nuxt.js community (#c24)

Doesn't handle native console string substitutions.

Version

v2.10.0

Reproduction link

https://codesandbox.io/embed/fervent-pine-su2ty

Steps to reproduce

Hi folks,

Consola is not handling the native string substitutions of console.
https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions

This leads to issues when when using wrapConsole method in code bases where you don't control logs.

Example: there is a problem with all the react errors.

Here an example before/after the wrap:

- Warning: Received `true` for a non-boolean attribute `secondary`.
+ Warning: Received `%s` for a non-boolean attribute `%s`.
  
- If you want to write it to the DOM, pass a string instead: secondary="true" or secondary={value.toString()}.
+ If you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.%s true secondary secondary true secondary 
    in h1 (created by App)
    in div (created by App)
    in App

For me, consola should have the same api than console, to be able to replace it properly.

How can we handle that?

Thanks for your work,
Matt'.

What is expected ?

Consola should have at least the same api and features than console.

What is actually happening?

Features from console are missing in consola (browser and node).

This bug report is available on Nuxt community (#c57)

Err Creating a new instance

import consola from 'consola'

const logger = consola.create({
// level: 4,
reporters: [
new consola.JSONReporter()
],
defaults: {
additionalColor: 'white'
}
})

Error TS2339 (TS) Property 'JSONReporter' does not exist on type 'Consola'.
Error TS2322 (TS) Type '{ additionalColor: string; }' is not assignable to type 'ConsolaLogObject'.
Object literal may only specify known properties, and 'additionalColor' does not exist in type 'ConsolaLogObject'.
i'm using code in document, but it have error. i don't nkow how to fix it. pls help me, thanks you very much.

This question is available on Nuxt community (#c58)

The page returned to the home page on wechat

Version

1.4.0

Reproduction link

https://jsfiddle.net/hqqxxf/edLsh8sL/

Steps to reproduce

in router '/a', it has a link to '/b', when I returned in '/b', The page returned to the home page('/') , and I found not the static resources request when returned.

What is expected ?

returned to the last page(router '/a')

What is actually happening?

returned to the home page(router '/' or 404)

This bug report is available on Nuxt.js community (#c30)

missing typescript definitions for reporters

Version

v2.11.3

Reproduction link

https://example.com

Steps to reproduce

import { Consola, FancyReporter } from 'consola';
will produce an error as there is no exported member FancyReporter

What is expected ?

to have proper detentions for the entire library

What is actually happening?

typescript error

This bug report is available on Nuxt community (#c70)

Object is undefined if not stringified (JSON.stringify)

I have an object to log.

I do this:

    console.log(professionnalInfos);
    logger.info(professionnalInfos);
    logger.info(JSON.stringify(professionnalInfos));

Result:

{ siren: '1111111', phone: '0511111111' }
ℹ info undefined
ℹ info {"siren":"1111111","phone":"0511111111"}

I think undefined is counter intuitive. No ?

This question is available on Nuxt.js community (#c26)

SyntaxError: Unexpected token ... on node 6.10.3

Version

v2.9.0

Reproduction link

[No link needed](No link needed)

Steps to reproduce

Create a file test.js and add following line:

var consola = require('consola');

What is expected ?

No errors when running on node 6.10.3

What is actually happening?

(function (exports, require, module, __filename, __dirname) { "use strict";function _interopDefault(u){return u&&"object"==typeof u&&"default"in u?u.default:u}var util=_int
eropDefault(require("util")),path=require("path"),fs=require("fs"),os=_interopDefault(require("os")),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=t
ypeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(u,e){return u(e={exports:{}},e.exports),e.exports}funct
ion getCjsExportFromNamespace(u){return u&&u.default||u}var vendors=[{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"Bamboo",c
onstant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITR
ISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDD
SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Default\Desktop\test.js:1:77)
This bug report is available on Nuxt community (#c54)

Uncaught TypeError: Illegal invocation while log.apply(void 0, ...

Version

2.8.1

Reproduction link

[http://not-available.com/Always broken on webview android 6.0.0](http://not-available.com/Always broken on webview android 6.0.0)

Steps to reproduce

Using android emulator with version 6.0.0

Having any consola.log will result in Uncaught TypeError: Illegal invocation due to https://stackoverflow.com/questions/8159233/typeerror-illegal-invocation-on-console-log-apply/8159338#8159338

The related snippet in consola/dist/consola.browser.js is

                return r(t, [{
                    key: "log",
                    value: function(e) {
                        var t = e.level < 1 ? console.__error || console.error : 1 === e.level && console.warn ? console.__warn || console.warn : console.__log || console.log
                          , r = "log" !== e.type ? e.type : ""
                          , s = e.tag ? e.tag : ""
                          , n = this.typeColorMap[e.type] || this.levelColorMap[e.level] || this.defaultColor
                          , i = "\n      background: ".concat(n, ";\n      border-radius: 0.5em;\n      color: white;\n      font-weight: bold;\n      padding: 2px 0.5em;\n    ");
                        t.apply(void 0, ["%c" + [s, r].filter(Boolean).join(":"), i].concat(o(e.args)))
                    }
                }]),

What is expected ?

Not throwing any exception in old browser

What is actually happening?

Throwing Uncaught TypeError: Illegal invocation

Additional comments?

Replace void 0 with console will resolve this for my case

This bug report is available on Nuxt community (#c50)

Maximum call stack size exceeded when using in combination with global-prefix

Version

v2.5.8

Reproduction link

https://codesandbox.io/s/14ljokmml4

Steps to reproduce

CodeSandbox: https://codesandbox.io/s/14ljokmml4 (unfortunately I can't get the CodeSandbox to run again after changing the nuxt.config.js and restarting. Please download the CodeSandbox and run locally to reproduce. Thx!)

  1. Install Nuxt
  2. Install and configure node-sass-magic-importer (see nuxt.config.js in CodeSandbox)
  3. Run npm run generate

What is expected ?

nuxt generate should do its job

What is actually happening?

100% CPU and nothing else seems to happen (because the developers of global-prefix use try / catch without logging the error).

Additional comments?

I've hunted down the error to the global-prefix package to the following lines: https://github.com/jonschlinkert/global-prefix/blob/master/index.js#L65

Add a console.error(err) in the catch section to see the Maximum call stack size exceeded error in node_modules/consola/dist/consola.js. Remove the try / catch block and just return null everything works fine.

Everything worked fine before Nuxt 2.5 so I assume something has changed with this package with the 2.5 release?

Thanks for the great work on Nuxt.js - I'm a big fan!

This bug report is available on Nuxt community (#c48)

consola v3 proposal

  • Use Proxy instead of creating closures for each log type. This allows using arbitrary log types and less overhead of tagged loggers and easier mocking
  • Find a way to make tagged loggers more lightweight when using withTag
  • Deprecate withDefaults and create (Keep for legacy but create a new class instance`
  • Support logs with timer (Using a token?)
  • Seperate <type>(logOjb) from <type>(args. (How?)
This question is available on Nuxt community (#c39)

docs: improve mocking guide

What problem does this feature solve?

It'd be great to have a few examples on how to mock consola (default, but also withScope) ☺️

We already have examples in the README, but a few more words to each wouldn't be bad ☺️

This feature request is available on Nuxt community (#c36)

TypeScript definitions

What problem does this feature solve?

I want to use consola in an express app written in TS, but for some reason definitions are excluded from final build published to NPM

This feature request is available on Nuxt community (#c41)

SyntaxError: Unexpected token ... for node 6.10.3

Version
2.9.0

Steps to reproduce
Create test.js and add:

var consola = require('consola');

What is expected ?
No errors when running node 6.10.3

What is actually happening?

(function (exports, require, module, __filename, __dirname) { "use strict";function _interopDefault(u){return u&&"object"==typeof u&&"default"in u?u.default:u}var util=_int
eropDefault(require("util")),path=require("path"),fs=require("fs"),os=_interopDefault(require("os")),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=t
ypeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(u,e){return u(e={exports:{}},e.exports),e.exports}funct
ion getCjsExportFromNamespace(u){return u&&u.default||u}var vendors=[{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"Bamboo",c
onstant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITR
ISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDD
SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Default\Desktop\test.js:1:77)
This question is available on Nuxt community (#c52)

Allow choosing util.format depth

What problem does this feature solve?

For large nested object (eg. Discord.js classes) consola doesn't have a level limit.

What does the proposed changes look like?

Add depth property to formatWithOptions

This feature request is available on Nuxt community (#c37)

SyntaxError: Unexpected token ... on node 6.10.3

Version
2.9.0

Steps to reproduce
Create a file test.js and add following line:

var consola = require('consola');

What is expected ?
No errors when running on node 6.10.3

What is actually happening?

(function (exports, require, module, __filename, __dirname) { "use strict";function _interopDefault(u){return u&&"object"==typeof u&&"default"in u?u.default:u}var util=_int
eropDefault(require("util")),path=require("path"),fs=require("fs"),os=_interopDefault(require("os")),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=t
ypeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(u,e){return u(e={exports:{}},e.exports),e.exports}funct
ion getCjsExportFromNamespace(u){return u&&u.default||u}var vendors=[{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"Bamboo",c
onstant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITR
ISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDD
SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Default\Desktop\test.js:1:77)
This question is available on Nuxt community (#c53)

Best to give a TS example

The project is almost an example of js. Can you provide an example of ts? thank you very much

This question is available on Nuxt community (#c55)

Maximum call stack size exceeded when using in combination with global-prefix

I hope this does not get deleted automatically, but https://nuxtjs.cmty.io/issues/new does not work!

Reproduction:

CodeSandbox: https://codesandbox.io/s/y0yxr7923j (unfortunately I can't get the CodeSandbox to run again after changing the nuxt.config.js and restarting. Please download the CodeSandbox and run locally to reproduce. Thx!)

  1. Install Nuxt
  2. Install and configure node-sass-magic-importer (see nuxt.config.js in CodeSandbox)
  3. Run npm run generate
  4. 100% CPU and nothing else happens (because the developers of global-prefix use try / catch without logging the error).

I've hunted down the error to the global-prefix package to the following lines: https://github.com/jonschlinkert/global-prefix/blob/master/index.js#L65

Add a console.error(err) in the catch section to see the Maximum call stack size exceeded error in node_modules/consola/dist/consola.js. Remove the try / catch block and just return null everything works fine.

Everything worked fine before Nuxt 2.5 so I assume something has changed with this package with the 2.5 release?

Thanks for the great work on Nuxt.js - I'm a big fan!

This question is available on Nuxt community (#c47)

nuxt:typescript: export assignment error in consola.d.ts

 ERROR in ./node_modules/consola/types/consola.d.ts(98,1):                                                          nuxt:typescript 11:30:28
    96 | export default consolaGlobalInstance
    97 | 
  > 98 | export = consolaGlobalInstance
       | ^
    99 | 
ℹ Version: typescript 3.7.4                                                                                                                                nuxt:typescript 11:30:28
ℹ Time: 15081ms                                                                                                                                            nuxt:typescript 11:30:28
ℹ Waiting for file changes                                                                                                                                                 11:30:28
ℹ Memory usage: 638 MB (RSS: 1.23 GB) 

nuxt-link openn an error : consola.info is not a function

Version

v2.10.0

Reproduction link

https://jsfiddle.net/boilerplate/vue

Steps to reproduce

Hello.

I have installed consola in my project and when I click on a nuxt-link who must display a log via Middleware I have an error : consola.info is not a function

If I refresh the page with my browser the log works well.

PS : an other project with nuxt 2.5.0 and consola 2.5.7 was working well

  • My middleware/log-router.js file
const consola = require('consola')

export default function (context) {
  consola.info('--> Info | request ' + context.route.fullPath + ' launched')
}
  • My nuxt.config.js file
export default {
  ...
  router: {
    // Run the middleware/log-router.js on every page
    middleware: 'log-router'
  }
}

Capture d’écran 2019-10-10 à 10.51.32.png

What is expected ?

Log a message

What is actually happening?

Blank page with error.

  • Page :
    consola.info is not a function
    An error occurred while rendering the page. Check developer tools console for details.

  • Console :
    vendors.app.js:11254 error TypeError: consola.info is not a function
    at app.js:3989
    at promisify (app.js:3422)
    at middlewareSeries (app.js:3401)
    at Vue.callMiddleware (app.js:943)
    at Vue._callee4$ (app.js:1069)
    at tryCatch (commons.app.js:6116)
    at Generator.invoke [as _invoke] (commons.app.js:6342)
    at Generator.prototype. [as next] (commons.app.js:6168)
    at asyncGeneratorStep (commons.app.js:31)
    at _next (commons.app.js:53)
    log @ vendors.app.js:11254
    log @ vendors.app.js:11166
    logFn @ vendors.app.js:11160
    logFn @ vendors.app.js:11084
    push../.nuxt/client.js.vue__WEBPACK_IMPORTED_MODULE_18
    .default.config.errorHandler @ app.js:680
    globalHandleError @ app.js:3101
    _callee4$ @ app.js:1319
    tryCatch @ commons.app.js:6116
    invoke @ commons.app.js:6342
    prototype. @ commons.app.js:6168
    asyncGeneratorStep @ commons.app.js:31
    _next @ commons.app.js:53
    Promise.then (async)
    asyncGeneratorStep @ commons.app.js:41
    _next @ commons.app.js:53
    (anonymous) @ commons.app.js:60
    (anonymous) @ commons.app.js:49
    _render @ app.js:1342
    render @ app.js:947
    iterator @ commons.app.js:10678
    step @ commons.app.js:10452
    (anonymous) @ commons.app.js:10453
    (anonymous) @ commons.app.js:10699
    _callee3$ @ app.js:805
    tryCatch @ commons.app.js:6116
    invoke @ commons.app.js:6342
    prototype. @ commons.app.js:6168
    asyncGeneratorStep @ commons.app.js:31
    _next @ commons.app.js:53
    (anonymous) @ commons.app.js:60
    (anonymous) @ commons.app.js:49
    _loadAsyncComponents @ app.js:842
    loadAsyncComponents @ app.js:736
    iterator @ commons.app.js:10678
    step @ commons.app.js:10452
    step @ commons.app.js:10456
    runQueue @ commons.app.js:10460
    confirmTransition @ commons.app.js:10707
    transitionTo @ commons.app.js:10609
    push @ commons.app.js:10919
    push @ commons.app.js:11300
    handler @ commons.app.js:9174
    invokeWithErrorHandling @ commons.app.js:13255
    invoker @ commons.app.js:13580
    original._wrapper @ commons.app.js:18303
    Show 14 more frames

This bug report is available on Nuxt community (#c60)

ci-info module throw error for "process is not defined"

Version

1.3.0

Reproduction link

https://codepen.io/timyaodpc/pen/bMyazm

Steps to reproduce

Use it in Nuxt/plugins/myplugin.js.

It all works but in browser console it give me a error says "process is not defined". Error points to "ci-info" module first line which tries to use process.env.

I can see ci-info is a dependency of consola as below:

└─┬ [email protected]
└─┬ [email protected]
└─┬ [email protected]
└── [email protected]

I now have to add isServer condition on const consola = require('consola'). Otherwise it breaks the client side.

What is expected ?

Browser should no error in console.

What is actually happening?

A error from ci-info says "process is not defined".

index.js:3 Uncaught ReferenceError: process is not defined
at Object../node_modules/ci-info/index.js (index.js:3)
at webpack_require (bootstrap 20212f6dd5b287d60bc9:712)
at fn (bootstrap 20212f6dd5b287d60bc9:117)
at Object../node_modules/is-ci/index.js (index.js:3)
at webpack_require (bootstrap 20212f6dd5b287d60bc9:712)
at fn (bootstrap 20212f6dd5b287d60bc9:117)
at Object. (index.js:1)
at Object../node_modules/std-env/index.js (index.js:18)
at webpack_require (bootstrap 20212f6dd5b287d60bc9:712)
at fn (bootstrap 20212f6dd5b287d60bc9:117)

Additional comments?

Is Consola can only be used in server side js?
The consola code index.js first line imported std-env which can only used in server side.
https://github.com/nuxt/consola/blob/master/src/index.js#L1
Not sure which is the best way to use it in Nuxt and maybe it's a bug?

This bug report is available on Nuxt.js community (#c32)

Fancy reporter hides nested structures

Version

v2.10.0

Reproduction link

https://repl.it/repls/RealDarkredOolanguage

Steps to reproduce

Create deeply (4 levels) nested object and try to log it.

What is expected ?

Whole object gets logged in the console.

What is actually happening?

Object is collapsed and part of it becomes simply [Object] hiding important info.

Additional comments?

This could be a configurable behaviour but I strongly belive that by default everything should be visible.

This bug report is available on Nuxt community (#c61)

An export assignment cannot be used in a module with other exported elements

how to solve this problem
ERROR in D:/web/test-nuxt-ts/node_modules/consola/types/consola.d.ts
ERROR in D:/web/test-nuxt-ts/node_modules/consola/types/consola.d.ts(98,1):
98:1 An export assignment cannot be used in a module with other exported elements.
96 | export default consolaGlobalInstance
97 |

98 | export = consolaGlobalInstance
| ^
99 |

FATAL Nuxt build error

This question is available on Nuxt community (#c65)

consola does not work under AudioWorkletGlobalScope

Version

v2.11.2

Reproduction link

https://codesandbox.io/s/gracious-mendel-uw0vh

Steps to reproduce

Functions like setTimeout and clearTimeout are not defined on https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletGlobalScope

Logging with consola uses these functions in order to throttle logging. It should be possible to disable the throttling or have consola disable throttling if these functions are not available.

Creating a worklet.js file with the following code:
console.log({setTimeout: typeof setTimeout, clearTimeout: typeof clearTimeout})

And another file, index.js with the following:
new AudioContext().audioWorklet.addModule("/worklet.js")

Outputs
{setTimeout: "undefined", clearTimeout: "undefined"}

What is expected ?

Consola to log without a crash

What is actually happening?

Consola code crashes

This bug report is available on Nuxt community (#c62)

consola.withScope is not a function in latest nuxt-edge

Version

2.0.0-25381228.14a6cd1

Reproduction link

n/a

Steps to reproduce

running yarn run dev produces this error

× fatal ...\nuxt\node_modules\@nuxtjs\axios\lib\module.js:1
   TypeError: consola.withScope is not a function
   at Object.<anonymous> (...\nuxt\node_modules\@nuxtjs\axios\lib\module.js:4:24)
   at Object.Module._extensions..js (module.js:671:10)
   at Object.Module._extensions..js (module.js:671:10)
   at Object.requireModule (...\nuxt\node_modules\nuxt-edge\dist\nuxt.js:1254:18)
   at Nuxt.requireModule (...\nuxt\node_modules\nuxt-edge\dist\nuxt.js:10262:21)
This bug report is available on Nuxt.js community (#c3)

bug: new LogLevel enum is not exported properly

In #94 I added/fixed the typings of the package.
As part of the process I added the LogLevel enum, which I exported in index.js.
When I tried to use the library, I realized that the npm package actually exports the the dist file, which is a minified version of node.js which doesn't export the new enum.
Also, it seems redundant to publish the src files if you expose a minified version.
@pi0 @Atinux I will prepare a quick fix not. Can you please give your opinion on the packaging of the src dir in the published package?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.