【问题标题】:Webpack compiling error if "require('dotenv').config()" is in index.js How can I fix?如果 index.js 中有“require('dotenv').config()”,则 Webpack 编译错误我该如何解决?
【发布时间】:2023-03-03 22:36:01
【问题描述】:

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

【问题讨论】:

    标签: javascript webpack dotenv


    【解决方案1】:

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

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

    请查看此链接。 https://github.com/mrsteele/dotenv-webpack/blob/master/README.md

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-14
        • 2019-07-15
        • 1970-01-01
        • 1970-01-01
        • 2013-03-29
        • 2021-07-08
        • 2013-03-17
        • 1970-01-01
        相关资源
        最近更新 更多