如果 "require('dotenv').config()" 在 index.js 中,Webpack 编译错误我该如何解决?

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

require('dotenv').config()导致webpack编译报错:

./node_modules/dotenv/lib/main.js 中的错误 26:11-24

找不到模块:错误:无法在 'C:\Users****\node_modules\dotenv\lib'

中解析 'os'

webpack 似乎无法处理 index.js 但我不明白为什么。

我的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);

请在webpack配置文件中使用。 (webpack.config.js)

另外,你需要安装dotenv-webpack包。

请看这个link。 https://github.com/mrsteele/dotenv-webpack/blob/master/README.md

new Dotenv() 添加到您的插件数组