Search code examples
javascriptwebpackdotenv

Webpack compiling error if "require('dotenv').config()" is in index.js How can I fix?


require('dotenv').config() cause webpack compiler error:

ERROR in ./node_modules/dotenv/lib/main.js 26:11-24

Module not found: Error: Can't resolve 'os' in 'C:\Users****\node_modules\dotenv\lib'

It seems like webpack can't handle in index.js but I can't understand why.

my webpack.config.js:

const path = require(`path`);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require(`clean-webpack-plugin`);

module.exports = {
  watch: true,

  mode: `development`,
  entry: {
    app: `./src/index.js`,
    profile: `./src/profile.js`
  },

  plugins: [
    new HtmlWebpackPlugin(),
    new CleanWebpackPlugin()
  ],
  output: {
    filename: `[name].bundle.js`,
    path: path.resolve(__dirname, `dist`)
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

index.js

require('dotenv').config()

import "./style.css";
const title = document.createElement("h3");
title.textContent = "Webpack made easy";
document.body.append(title);
title.classList.add("hello");
console.log(process.env.API_KEY);


Solution

  • Please use it in webpack configuration file. (webpack.config.js)

    Also, you need to install dotenv-webpack package.

    Please look at this link. https://github.com/mrsteele/dotenv-webpack/blob/master/README.md