【问题标题】:dotenv not working with serverless/webpackdotenv 不适用于无服务器/webpack
【发布时间】:2018-10-19 19:14:40
【问题描述】:

编辑:如果我注销 dotenv.config(),我会收到以下错误:Error: ENOENT: no such file or directory, open '/Users/myPathToApplication/.webpack/test/.env'

我正在捆绑我的无服务器处理程序以使用 es6/es7 代码。我也尝试使用一些env 变量。问题是,当我捆绑处理程序时,dotenv 似乎不起作用。

例如,我使用的工具之一是将mongoose 连接到我的应用程序。在这里,我将DB_URI 存储为环境变量。从'envdotjs'导入envdotjs;

import mongoose from 'mongoose';
mongoose.Promise = global.Promise;
require('dotenv').config();
let isConnected;

const connectToDatabase = () => {
  if (isConnected) {
    console.log('=> using existing database connection');
    return Promise.resolve();
  }
  console.log('=> using new database connection');
  return mongoose.connect(process.env.DB_URI).then(db => {
    isConnected = db.connections[0].readyState;
  });
};

module.exports = {
  connectToDatabase
};

但是DB_URI 未定义并且代码中断。

这是我的 webpack:

const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: slsw.lib.entries,
  target: 'node',
  devtool: 'source-map',
  externals: [nodeExternals()],
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: __dirname,
        exclude: /node_modules/
      }
    ]
  }
};

我运行它是为了在运行良好的无服务器处理程序上使用 es6/7。但是环境变量正在破坏。我还尝试使用一个名为envdotjs 的模块,得到的结果与未定义环境变量相同,所以我认为dotenv 没有问题。

【问题讨论】:

  • 在更糟糕的情况下,您可以在无服务器配置中将环境变量 sunder provider > environment 移动。你也可以试试dotenv-webpack
  • Bout 发布 dotenv-webpack 的答案

标签: javascript node.js webpack environment-variables serverless-framework


【解决方案1】:

我发现@apokryfos 也推荐了一个包dotenv-webpack。只需在 const Dotenv = require('dotenv-webpack') 中要求它并将其包含在 webpack.config.js 中即可。

module.exports = {
...
  plugins: [new Dotenv()]
}

只需将您的.env 与您的webpack.config.js 一起包含在根目录中,您就可以在任何需要的地方声明您的process.env.,无需其他配置。

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 2016-05-18
    • 2021-11-19
    • 2019-11-26
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2013-06-13
    • 2019-09-08
    相关资源
    最近更新 更多