如何在 javascript 中使用 dotenv 和 import

问题描述 投票:0回答:1

我想通过node.js使用dotenv 我已经尝试过“require”,但浏览器不支持它。在文档中,建议使用 ES6 导入,我就是这样做的,但仍然存在我正在尝试解决的错误。

在index.mjs 文件中,我完全按照文档中的方式导入了dotenv。

import 'dotenv/config'
dotenv.config();

我收到错误:未捕获类型错误:无法解析模块说明符“dotenv/config”。相对引用必须以“/”、“./”或“../”开头。 所以我修改了代码

import '/dotenv/config'
dotenv.config();

我收到另一个错误:GET http://...../dotenv/config 404(未找到)

我需要帮助,因为我无法让代码工作。我在文件夹的根目录下安装了 Node.js 以及“.env”。这是我的 package.json。

{
  "name": "testnode",
  "version": "1.0.0",
  "description": "nodeTest",
  "main": "index.mjs",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "airtable": "^0.12.1",
    "browserify": "^17.0.0",
    "dotenv": "^16.3.1",
    "express": "^4.18.2"
  }
}
javascript node.js import require dotenv
1个回答
0
投票

如果你的软件包安装正确的话,它应该像这样简单:

import dotenv from "dotenv";
dotenv.config();

我已经尝试过了,似乎有效。

import express from "express";
import dotenv from "dotenv";
const app = express();
dotenv.config()

app.listen(process.env.BACKEND_PORT, ()=>{
    console.log(`Server started at ${process.env.BACKEND_PORT}`)    
})

我不确定你所说的“但浏览器不支持它”是什么意思,因为环境变量一开始就不能直接从浏览器访问。

© www.soinside.com 2019 - 2024. All rights reserved.