2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

vite.config.jsに.envの環境変数を読み込む

Last updated at Posted at 2023-02-02

環境

Vite 4.0.0
Vue 3.2.45

.envとpackage.json

--modeなしなら.env、--modeを付けて.env.hogeを読み込んだり。

package.json
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "build_hoge": "vite build --mode hoge",
    "preview": "vite preview"
  }

環境変数の先頭には必ず「VITE」をつける必要あり。

.env
VITE_APP_PATH='/dist/'
.env.hoge
VITE_APP_PATH='/hoge/'

vite.config.js

defineConfig()をreturnする形に変更して、今回は以下のようにbaseキーに環境変数を設定した。

vite.config.js
export default ({ mode }) => {
  process.env = {...process.env, ...loadEnv(mode, process.cwd())};

  return defineConfig({
      base: process.env.VITE_APP_PATH,
      plugins: [vue()],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
      },
  });
}

npm run build、npm run build_hogeなど実行して、アセットのパスが変わってることを確認。
できました。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?