nuxt3 plugins错误[warn] [nuxt]的解决办法以及思考

2,182 阅读2分钟

最近在用nuxt3开发公司的项目,遇到nuxt3 plgins的错误,一开始真的很懵,后面解决了,也加深了对nuxt3 plugine的理解,所以记录下。

报错提示


// 没有在provide里面返回一个函数
[warn] [nuxt] Some plugins are not exposing a function and skipped: [
  {
    success: [Function: success],
    warn: [Function: warn],
    error: [Function: error]
  }
]


// 插件加载了  但是没有用defineNuxtPlugine声明为一个功能插件
[warn] [nuxt] You are using a plugin that has not been wrapped in `defineNuxtPlugin`. It is advised to wrap your plugins as in the future this may enable enhancements: message

还是先介绍下这些错误大概是因为什么方式引起的

[warn] [nuxt] Some plugins are not exposing a function and skipped

这个错误意味着,可能你在index.js或者index.ts中导出的不是一个函数,然后在provide中使用的不是一个函数。

官方示例

export default defineNuxtPlugin(() => {
  return {
      provide: {
          hello: (msg: string) => `Hello ${msg}!` 
          } 
         }
        })

nuxt3中,更新了自动导入的功能,只要是在第一级文件导出的插件,都可以被nuxt加载进来,还有二级目录下面index文件,nuxt3也会加载进来。如果是想要在全局中使用的话,必须通过provide这个属性把插件抛出去,这样就可以像vue那样使用。但是必须确保你传入的值是一个函数,如果传入的不是函数,就会提示这个错误,当然,也有一种情况也会导致这个错误,就是你在index.js中导出的不是一个函数,所以也是会引起这个错误提示。

解决办法

因为是导出或者provide不是一个函数,所以我们只需要返回一个函数就可以了。

[warn] [nuxt] You are using a plugin that has not been wrapped in defineNuxtPlugin. It is advised to wrap your plugins as in the future this may enable enhancements: message

这个错误的意思是我们在plugins/目录下面的文件有个插件是没有用defineNuxtPlugin去声明,或者就是你的二级目录下面的index.js是没有使用一个defineNuxtPlugin声明,这样也是会提示这个错误。

解决办法

这个错误处理很简单,就是在要抛出的插件外面包裹一层defineNuxtPlugin就好了。

收获

在没有遇到这个错误的时候,对nuxt3的plugin并不是很理解,然后这里面自动导入忽视了二级目录下面index.js或者index.ts是会被导入的,不需要我们在plugins/下面新建一个index.ts/index.js来注册插件。