Home > front end >  Nuxt injection not found
Nuxt injection not found

Time:03-15

What am I doing wrong when injecting a logger to the Nuxt instance?

loglevel.client.js

import log from 'loglevel';

log.setLevel(process.env.LOG_LEVEL || 'debug');

export default ({ app }, inject) => {
  inject('log', log);
  log.debug('logger set up')
}

nuxt.config.js

  plugins: [
    '~/plugins/loglevel.client.js',
    '~/plugins/api.js',
  ],

plugins\api.js

if (process.client) {
  console.log('on client console')
  this.$log.error('on client $log')
}

browser:

api.js?e568:4 on client console
08:22:26.456 api.js?e568:5 Uncaught TypeError: Cannot read properties of undefined (reading '$log')
    at eval (api.js?e568:5:1)
    at Module../plugins/api.js (app.js:1033:1)

CodePudding user response:

inject makes $log available elsewhere by attaching it as a property to both the root Vue app and to the Nuxt context.

Plugins are ran before the root Vue app is instantiated— you can't access $log via this.$log, unless this refers to the root Vue app instance (like it does in components).

Instead you'll have to access $log via the Nuxt context, which is conveniently available as the first argument to your api.js plugin.

export default ({ $log }) => {
  if (process.client) {
    console.log('on client console')
    $log.error('on client $log')
  }
}

From the docs:

The (Nuxt) context provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas like asyncData , fetch , plugins , middleware and nuxtServerInit.

Also, it looks like loglevel is registered as a client-side plugin (loglevel.client.js). That code will not run server side— so you don't have to wrap anything within process.client.

  • Related