1
4

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.

webpack + Pug :テンプレート内で環境変数を取得

Last updated at Posted at 2020-09-13

0.前提

  • webpack4
  • pug-html-loader

1.package.jsonのscriptsで環境変数を設定

  • npmでcross-envをインストールし、Mac/Winどちらでも動くようにする。
package.json
  "scripts": {
    "build:prd": "cross-env NODE_ENV=production webpack --mode production",
    "build:stg": "cross-env NODE_ENV=staging webpack",
    "build:dev": "cross-env NODE_ENV=develop webpack"
  },

2. pugのテンプレート内で環境変数取得

  • pugを置換するときnodeのライブラリが使えるので、nodeのprocessをつかって環境変数を取得。
  • 定義したファイルは他のテンプレートで読みこむようにする。
def.pug

//nodeのprocessを通じて環境変数を取得
var appEnv = process.env.NODE_ENV;

//環境変数によってpathのルートを変更
var pathRoot = (['develop', 'production'].includes(process.env.NODE_ENV) ) ? "/" : "/stg/";

3. 共通変数を各ページで読み込む

  • 項番2で定義した「def.pug」を書くページで読み込む。
page.pug

include /_includes/def.pug

doctype html
html(lang="ja")
 body
   a(href=pathRoot+"test.html") テスト

備考

webpkacの他のライブラリもこのような感じで環境変数が取れるのではないでしょうか?

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?