0
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 1 year has passed since last update.

Nuxtで環境変数を分ける

Last updated at Posted at 2023-05-31

開発時とビルト時で環境変数を分けたかった。

まず、runtimeConfigで変数を使えるようにする。

nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiTest: 'hogehoge',
    },
  },
...

これで任意の場所で変数が使えるようになる。

const runtimeConfig = useRuntimeConfig();
console.log(runtimeConfig.public.apiTest);

次に、.env.devと.env.productionの2つのファイルを作って、
変数の中身をそれぞれ書き込む。

この時に、頭にNUXT_をつけて、
nuxt.config.tsのruntimeConfigの変数と名前を合わせると、
runtimeConfigが.envで上書きされる。

.env.dev
NUXT_PUBLIC_API_TEST = "https://test-dev.com/api/"

.env.production
NUXT_PUBLIC_API_TEST = "https://test-production.com/api/"

コマンド実行時に.envファイルを使い分ける。

package.json
"scripts": {
    "dev": "nuxt dev --dotenv .env.dev",
    "generate": "npx nuxi generate --dotenv .env.production",
...
  

参考


やっぱり上記のやり方よりこっちの方がいいかも

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