1
0

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.jsでCSSとJSを別々のファイルに出力する方法

Last updated at Posted at 2022-04-27

Nuxt.jsのデフォルトの設定では、CSSとJSが同一のファイルに出力されます。
本記事では、CSSとJSを別々のファイルに出力する方法を解説します。

CSSファイルのみをキャッシュさせたい場合などに有効かと思います。

nuxt.config.jsにextractCSSを追加する

nuxt.config.js
export default {
  build: {
    /*
     ** You can extend webpack config here
     */
    extend() {},
    extractCSS: true /* 追加 */
  }
}

Nuxt.jsのnuxt.config.jsファイルにextractCSS: trueを追記します。(デフォルトではfalse)

上記の設定でJSとCSSを別ファイルで出力することができます。

出力するファイル名やディレクトリを指定する

出力するファイル名やディレクトリを指定することもできます。

nuxt.config.js
export default {
  build: {
    extend() {},
    extractCSS: true,
    filenames: {
      app: ({ isDev }) => (isDev ? '[name].js' : '[id].[contenthash].js'),
      chunk: ({ isDev }) => (isDev ? '[name].js' : '[id].[contenthash].js'),
      css: ({ isDev }) => (isDev ? '[name].css' : 'css/[contenthash:7].css')
    }
  }
}

https://nuxtjs.org/docs/configuration-glossary/configuration-build/#filenames

出力するファイル名を固定にする

nuxt.config.js
export default {
  build: {
    extend() {},
    extractCSS: true,
    filenames: {
      app: () => '[name].js',
      chunk: () => '[name].js',
      css: () => '[name].css'
    }
  }
}

固定のファイル名にした場合は、ブラウザにキャッシュされて変更を検出できない可能性があるので注意が必要になります。

参考

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?