LoginSignup
3
0

More than 5 years have passed since last update.

nuxtで環境(development/production)ごとに別の内容でファイルを配置したい

Last updated at Posted at 2018-10-04

2018.10.4 nuxt-1.4

例えば、robots.txtだったり、DNS認証用ファイルだったり、pwaのmanifest.jsonだったり apple-app-site-associationファイルだったり、faviconだったり、環境別に(ほぼ)静的ファイルを配置わけしたい場合。

1. 専用ライブラリを探して使う

robots.txtや、manifest.jsonの場合は、専用のライブラリがある
https://www.npmjs.com/package/nuxt-robots-module
https://github.com/nuxt-community/pwa-module

2. nuxt.config.jsのbuild設定に差し込む

buildのextendでwebpackの設定をカスタマイズできるので、copy-webpack-pluginでもcpxでもなんか使ってどうにかすればどうにかなりそうだけど、実際試してないので詳細不明。

3. 自力でmoduleでファイル書き出し対応する。

nuxtのwebpack設定ってあまりいじりたくなくて、結局とりあえずの処置としてこれで対応した。nuxt dev, nuxt build, nuxt generate で動いた。

例えばrobots.txtの場合

/modules/robots-txt.js
const resolve = require('path').resolve
const fs = require('fs')

module.exports = function RobotsTxtModule(moduleOptions) {

  const isDev = this.options.dev
  const filename = 'robots.txt'
  const content = !isDev
    ? `User-agent: *
Allow: /`
    : `User-agent: *
Disallow: /`

  // generate 用にフックを追加する
  this.nuxt.hook('generate:done', async generator => {
    const path = resolve(this.options.generate.dir, filename)
    fs.writeFileSync(path, content)
  })

  // devまたはssr向け
  this.addServerMiddleware({
    path: filename,
    handler(req, res) {
      res.setHeader('Content-Type', 'text/plain');
      if (res.send) {
        res.send(content);
      } else {
        res.end(content, 'utf-8');
      }
    },
  })
}
nuxt.config.js

module.exports = {
  // ... (略) ...
  modules: [
    ["~/modules/robots-txt"],
  ],
  // ... (略) ...
}
3
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
3
0