unjs / consola

🐨 Elegant Console Logger for Node.js and Browser
Other
6.12k stars 175 forks source link

is there a way to require consola throughout nuxt app in order to avoid requiring in each file? #114

Closed tansaku closed 1 year ago

tansaku commented 3 years ago

Just wondering if there's a simple way to require consola in, say, nuxt.config.js in such a way that it's available throughout a nuxt project without having to require it in every file?

samtgarson commented 3 years ago

You can use a Nuxt plugin and the inject function to inject the consola instance into every Vue context, e.g.


const logger = {{ instantiate consola with options }}
export default ({ app }, inject) => {
  inject('logger', logger)
}

// in components:
export default {
  methods {
    someMethod () {
      this.$logger('mounted')
    }
  },
  asyncData({ app, $logger }) {
    $logger('asyncData')
    // If using Nuxt <= 2.12, use 👇
    app.$hello('asyncData')
  }
}
pi0 commented 1 year ago

We might introduce a runtime built-in logger for nuxt but in the meantime, it is better to not use consola directly in runtime plugins. It is not designed exactly for that.