无法解析模块说明符“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"。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)