0

Here is my webpack.config.js file for my react project.

const deps = require("./package.json").dependencies;
console.log({API_URL:process.env.API_URL})
module.exports = (env) => {
  console.log({API_URL:process.env.API_URL})
  return {
    mode: env.file,
    output: {
      publicPath: "http://localhost:8000/",
    },
    resolve: {
      extensions: [".tsx", ".ts", ".jsx", ".js", ".json"],
      alias: {
        'react': path.resolve(__dirname, 'node_modules/react'),
        'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
      }
    },
    devServer: {
      port: 8000,
      historyApiFallback: true,
    },
    module: {
      rules: [...],
    },
    plugins: [
      new HtmlWebPackPlugin({
        template: "./public/index.html",
      }),
      new Dotenv({
        path: `./.env${env.file ? `.${env.file}` : ''}`
      })
    ],
  }
};

Why I am getting undefined here in the API_URL? How can I use env variable in webpack.config.js?

  • Did you read https://webpack.js.org/guides/environment-variables/ and also see this question https://stackoverflow.com/questions/58441255/dotenv-webpack-use-environment-variable-in-webpack-config-js – Lin Du Apr 21 '23 at 11:00
  • @LinDu So I need to pass the --env variables in command(package.json) itself? 1) What if I have large number of variables and 2) Env variables should be kept in package.json as they should be confidential information? – Ashish Choudary Apr 21 '23 at 11:06
  • Does this https://stackoverflow.com/a/46232148/6463558 answer your question? – Lin Du Apr 21 '23 at 12:48

0 Answers0