首页 > 解决方案 > 无法解析模块说明符“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”。

标签: javascriptnode.jsdotenv

解决方案


推荐阅读