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

Reactでenvを導入したらエラーが起きた

Posted at

前提

フロントエンドでwebpackを使用して開発をしている

下記が設定していたwebpack.config.js

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
  mode: "development",
  entry: path.resolve(__dirname, "./src/index.tsx"),
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index.js",
  },
  resolve: {
    modules: [path.resolve(__dirname, "node_modules")],
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: [/\.ts$/, /\.tsx$/],
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"],
              plugins: ["@babel/plugin-transform-runtime"],
            },
          },
        ],
      },
      {
        test: /\.png/,
        type: "asset/resource",
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "./src/index.html"),
    }),
  ],
  devServer: {
    port: 8111,
    static: {
      directory: path.join(__dirname, "dist"),
    },
  },
}

今まで

yarn add dotenvコマンドを実行し、envを使用する際に下記のように記入していた

index.ts

import dotenv from "dotenv"

dotenv.config()        

process.env.〇〇

エラー

ターミナルでnpx webpack serve --config webpack.config.jsを叩いてブラウザで描画させようとしたら、
ERROR in ./node_modules/dotenv/lib/main.jsというエラーが出た...

解決策

yarn add -D dotenv-webpack
コマンドを実行し、dotenv-webnpackを導入

webpack.config.jsに追加

const Dotenv = require("dotenv-webpack")
module.exports = {
省略
plugins: [
    new Dotenv(),
  ],
 }

index.ts

const { TEST } = process.env //分割代入
const test = TEST

必要だと思っていた下記を記入しなくてよくなった!

import dotenv from "dotenv"
dotenv.config()       

最後に

解決するまで意外と時間がかかってしまったので作成しました。
今まではNode.jsだったのでenvの使い方が違っていました...

参考記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?