LoginSignup
1
0

More than 1 year has passed since last update.

[javascript] env使いたい時にでたエラー

Last updated at Posted at 2022-03-26

javascriptで環境変数を使いたい。
node_moduleのdotenvを入れたのだけどうまく動かなかった時の忘備録

環境
es6
typescript
webpack

手順

  1. npm install dotenv --save
  2. .envをproject直下に作成
.env
SECRET_KEY="HOGE"
  1. 呼び出し
index.ts
import 'dotenv/config'
const PRIVATE_KEY = process.env.PRIVATE_KEY;

エラー1

確かにあるのになぜかモジュール読み込めていない。

ERROR in ./node_modules/dotenv/config.js
Module not found: Error: Can't resolve './lib/cli-options' in '[...]/node_modules/dotenv'
 @ ./node_modules/dotenv/config.js 6:6-34
 @ ./src/index.ts

ERROR in ./node_modules/dotenv/config.js
Module not found: Error: Can't resolve './lib/env-options' in '[...]/node_modules/dotenv'
 @ ./node_modules/dotenv/config.js 5:6-34
 @ ./src/index.ts

ERROR in ./node_modules/dotenv/config.js
Module not found: Error: Can't resolve './lib/main' in '[...]/node_modules/dotenv'
 @ ./node_modules/dotenv/config.js 2:2-23
 @ ./src/index.ts

解決法

拡張子の'.js'が抜けてた。
tsの拡張子を省略できる一方でjsを書き忘れると拡張子の解決ができなくなるみたい!

webpack.config.js
module.exports = {
    // ...
    resolve: {
        extensions: ['.ts', '.js'],
    },
}

エラー2

ERROR in ./node_modules/dotenv/lib/main.js
Module not found: Error: Can't resolve 'fs' in '[...]/node_modules/dotenv/lib'
 @ ./node_modules/dotenv/lib/main.js 1:11-24
 @ ./node_modules/dotenv/config.js
 @ ./src/index.ts

解決法

割とみんな出会っているみたい。
fsはnodeのポリフィルのために使っているみたいで、フロントでは必要ないので以下の設定を追加すれば良いらしい
参考:Can't resolve 'fs'

webpack.config.js
module.exports = {
    // ...
    node: { fs: 'empty' }
}
1
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
1
0