javascript - 无法解析模块说明符“dotenv”。相对引用必须以“/”、“./”或“../”开头
问题描述
我正在尝试将我的 API 密钥存储在 .env 文件中并在 news.js 中获取密钥,但出现错误“无法解析模块说明符“dotenv”。相对引用必须以“/”、“./”或“../”开头。
/*news.js*/
import dotenv from 'dotenv'
dotenv.config()
const apiKey = process.env.API_KEY
console.log(key);
document.addEventListener('DOMContentLoaded', () => {
fetch(`https://newsapi.org/v2/everything?q=covid&apiKey=${key}`)
.then(res => res.json())
.then(data => {
renderArticles(data)
})
})
/*news.html*/
<script type="module" src="js/news.js"></script>
/*index.js*/
import dotenv from 'dotenv'
dotenv.config();
const apiKey = process.env.API_KEY
console.log(apiKey);
我也在 package.json 上添加了“type”:“module”。
解决方案
推荐阅读
- mysql - MySQL 的 JSON_ARRAY_APPEND 有什么相反的吗?
- .net - 调试 .NET Web 应用程序遇到拒绝访问错误
- powershell - Azure DevOps Pipeline - Power shell 脚本,使用变量复制文件
- c# - Nunit 测试项目 net45 使用 Costura.Fody 在 Release 中成功并在 Debug 中失败并出现异常
- laravel - laravel:更新记录时发送带有(数据)的通知
- c# - 在 C# Winforms 应用程序中异步上传多个文件
- java - Avro 序列化/反序列化到/从 Kafka 主题
- apache-spark - S3 Select 会加速 Parquet 文件的 Spark 分析吗?
- powerbi - 如何正确使用 Table.Repeat 功能?
- python-3.x - 图例上有多个标记