1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Nuxt】pluginsにはexport default を付けよう

Last updated at Posted at 2021-03-01

Nuxt.jsのpluginsを使っててハマった話

結論

pluginはexport default しようぜって話

~/plugins/plugin.js
export default () {
  // 処理
}

背景

pluginはnuxt.config.jsの上から順番に実行されるが、export defaultをしないと順番通りに実行されない。

nuxt.config.js
  // first→second→thaad の順番で実行される
  plugins: [
    {
      src: '~/plugins/first.js',
      mode: 'client'
    },
    {
      src: '~/plugins/second.js',
      mode: 'client'
    },
    {
      src: '~/plugins/thaad.js',
      mode: 'client'
    },
  ]

理由

下記のようにpluginsがbuildされるが、
export defaultをしていないと、importされた時点で即コードを実行するので順番通りにならない。

_nuxt/index.js
/* Plugins */
import nuxt_plugin_first_08b2fdac from 'nuxt_plugin_first_08b2fdac' // Source: ./first.js (mode: 'client')
import nuxt_plugin_second_18f96a7c from 'nuxt_plugin_second_18f96a7c' // Source: ./second.js (mode: 'client')
import nuxt_plugin_thaad_68e7ee02 from 'nuxt_plugin_thaad_68e7ee02' // Source: ./thaad.js (mode: 'client')

if (process.client && typeof nuxt_plugin_first_08b2fdac === 'function') {
  await nuxt_plugin_first_08b2fdac(app.context, inject)
}
if (process.client && typeof nuxt_plugin_second_18f96a7c === 'function') {
  await nuxt_plugin_thaad_68e7ee02(app.context, inject)
}
if (process.client && typeof nuxt_plugin_thaad_68e7ee02 === 'function') {
  await nuxt_plugin_thaad_68e7ee02(app.context, inject)
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?