LoginSignup
2
2

More than 3 years have passed since last update.

VuePressのVueコンポーネントで環境変数を使いたいとき

Last updated at Posted at 2019-11-17

vuepress にてVueコンポーネント内で環境変数を使おうとした際に若干ハマったので共有しておきます。
(2019/11/24 追記: 以前の方法ではproductionビルド時に環境変数読み込めないので修正しました)

バージョン

  • vuepress 1.2.0
  • dotenv 8.2.0

ディレクトリ構成

- /
  - src/
    - .vuepress/
      - config.js
      - components/
        - Component.vue
  - .env
  - package.json

環境変数は .env に書かれています。

/.env
HOGE=123

Component.vue 内で環境変数を参照したい。

解決策

webpack 内では process.env は参照できないため config.jsenvファイル を読み込み webpack へ渡します。

yarn add --dev dotenv

ドキュメント によると configureWebpack には Objectfunction である必要があるようです。 Object の場合は webpack-merge を使用してマージされるようです。

/src/.vuepress/config.js
const webpack = require('webpack')
const { config } = require('dotenv')
config()

module.exports = {
  title: 'Sample',
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'HOGE': JSON.stringify(process.env.HOGE)
        }
      })
    ]
  },
  ...
}

こうすることでDeevelopment buildの際は .env から環境変数が参照され、Netilify等のProduction buildの際は設定されているビルド時の環境変数がwebpackへ渡されます。
これで、vuepress 内のコンポーネントから参照できるようになりました。

/src/.vuepress/components/Component.vue
<template>
  <div></div>
</template>

<script>
export default {
  name: 'Works',
  mounted() {
    console.log(process.env.HOGE) // 123
  }
}
</script>
2
2
1

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