6
7

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] cross-envを使い環境に応じてbaseURLを分ける

Last updated at Posted at 2020-06-17

cross-envを導入

yarn add cross-env

環境変数を作成

env ディレクトリを作成し、環境変数として使う値を作成する。今回はBASE_URLのみとする。

env/local.ts
module.exports = {
  BASE_URL: '/'
}

Github Pagesならリポジトリ名を入れる

env/production.ts
module.exports = {
  BASE_URL: '/somethings/'
}

package.jsonのscriptsを編集

devやbuildコマンドにcross-envを仕込む

package.json

{
  "scripts": {
    "dev": "cross-env NODE_ENV=\"local\" nuxt-ts --port=3003",
    "build": "cross-env NODE_ENV=\"production\" nuxt-ts build"
  }
}

nuxt.configで参照する

nuxt.config.ts
const environment = process.env.NODE_ENV || 'local'
const env = require(`./env/${environment}.ts`)

// 気になればログ吐いてデバッグ
console.log(env)

module.exports = {
  router: {
    base: env.BASE_URL
  }
  env: env
}

参考

Nuxtでcross-envを使い環境ごとに環境変数を分ける - Qiita

6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?