google-maps - 将 Google Maps API 添加到 Gatsby 项目时出现“错误:无法解析“fs”
问题描述
TL;DR -
Module not found: Error: Can't resolve 'fs' in '[MY-PATH]/node_modules/dotenv/lib'
尝试在我的 Gatsby 项目中实现 Google Maps API。
你好,
我正在 Gatsby 中开发 Yelp Clone 作为个人项目,以添加到我的投资组合中。现在,我在将 Google Maps API 的“香草”实现引入我的地图组件时遇到了一些问题。
到目前为止,这是我Map
设置应用程序组件的方式:
地图.js
import React, { useEffect } from "react";
require("dotenv").config({
path: `.env`
});
const MAPS_API_KEY = process.env.MAPS_API_KEY;
const Map = () => {
useEffect(() => {
window.initMap = initMap;
runScript(
`https://maps.googleapis.com/maps/api/js?key=${MAPS_API_KEY}&callback=initMap`
);
});
const initMap = () => {
// Declare map object
new window.google.maps.Map(document.getElementById("map"), {
center: { lat: 39.952583, lng: -75.165222 },
zoom: 14
});
};
return <div id="map" />;
};
export default Map;
function runScript(src) {
const body = window.document.querySelector("body");
const script = window.document.createElement("script");
script.src = src;
script.async = true;
script.defer = true;
body.insertAdjacentElement("beforeend", script);
script.onerror = () => {
throw new Error("Failed to load Google Maps");
};
}
总之,底部函数runScript
采用 Map 的 URL 并在结束标记之前<script>
向对象添加一个标记。window.document
<body>
基于我从事的另一个项目,其中初始化地图的调用是在内部设置的componentDidMount
,我已经设置了要在'runScript
调用内部调用的函数,该函数首先用于初始化地图 ( )。Map
useEffect
initMap
但是,我在重新构建应用程序时遇到的错误表明'fs'
,似乎与我对 dotenv 库的使用有关的值有问题:
控制台错误
Error: ./node_modules/dotenv/lib/main.js
Module not found: Error: Can't resolve 'fs' in '[MY-PATH]/node_modules/dotenv/lib'
resolve 'fs' in '[MY-PATH]/node_modules/dotenv/lib'
我的 .env 文件内容
YELP_API_KEY=[API-VALUE]
MAPS_API_KEY=[API-VALUE]
到目前为止,对这个错误的研究让我在网上看到了各种文章,这些文章暗示我应该对 Gatsby 的 webpack 配置进行更改,以便接受我的环境变量。由于设置自定义 webpack 配置显然需要几个步骤来以编程方式更改项目的 webpack 文件,并且 Gatsby 文档中关于此主题提供的示例不容易转移到我自己的问题上,因此我一直在寻找解决问题的其他可能性问题,但仍然难倒。
任何帮助或提示帮助我朝着正确的方向前进,显然将不胜感激。
同时,我将通读 Webpack 文档。
谢谢。
环境和配置设置:
- 以下一些文件可能与当前问题无关,但是,Gatsby 鼓励您在报告问题时包含以下详细信息,因此:
项目环境版本
- 盖茨比版本:2.1.4
- Node.js 版本:10.15.0
- 操作系统版本:10.14.4
盖茨比-config.js
require("dotenv").config({
path: `.env`
});
module.exports = {
siteMetadata: {
title: `Yelp Clone App`,
description: `A simple clone of Yelp for viewing Mexican restaurants in the Philadlephia area`,
author: `Jamie Strausbaugh`
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-yelp`
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `phillyMex`,
path: `${__dirname}/src/data/`
}
}
]
};
包.json
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "0.1.0",
"author": "Kyle Mathews <mathews.kyle@gmail.com>",
"dependencies": {
"dotenv": "^7.0.0",
"gatsby": "^2.1.4",
"gatsby-image": "^2.0.29",
"gatsby-plugin-manifest": "^2.0.17",
"gatsby-plugin-offline": "^2.0.23",
"gatsby-plugin-react-helmet": "^3.0.6",
"gatsby-plugin-sharp": "^2.0.20",
"gatsby-source-filesystem": "^2.0.29",
"gatsby-transformer-json": "^2.1.11",
"gatsby-transformer-sharp": "^2.1.13",
"prop-types": "^15.7.2",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"react-helmet": "^5.2.0"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "GATSBY_GRAPHQL_IDE=playground gatsby develop",
"start": "npm run develop",
"serve": "gatsby serve",
"test": "echo \"Write tests! -> https://gatsby.app/unit-testing\""
},
"repository": {
"type": "git",
"url": "https://github.com/gatsbyjs/gatsby-starter-default"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
}
盖茨比-node.js
const path = require(`path`);
exports.createPages = async function({ actions, graphql }) {
// Query for restaurant nodes to use in creating pages
return await graphql(`
{
allYelpBusiness {
edges {
node {
alias
name
image_url
url
review_count
categories {
title
}
rating
coordinates {
latitude
longitude
}
price
location {
display_address
}
display_phone
}
}
}
}
`).then(result => {
// Create pages for each restaurant
result.data.allYelpBusiness.edges.forEach(({ node }) => {
actions.createPage({
// Path for this page is required
path: node.alias,
component: path.resolve(`./src/templates/venueDetails.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables
alias: node.alias
}
});
});
});
};
解决方案
虽然它没有为我解决问题,但很多遇到此错误的人都对这个解决方案很幸运:
- 删除
package-lock.json
和/或yarn.lock
- 发出
gatsby clean
清除任何陈旧数据的问题。- 删除
node_modules
文件夹。- 使用您选择的包管理器(npm 或 yarn)再次安装依赖项。
- 发出
gatsby develop
并查看错误是否不会弹出。
推荐阅读
- angular - 错误:this.currentLoader.getTranslation(...).pipe 不是函数
- db2 - 无法创建 DATE 数据类型的 db2 表
- package - 如何在 julia 中注册或提供手动解压缩的包给其他包?
- c++ - C++ - 用户空间代码中的第二级受保护代码
- reactjs - 如何对包含对象的 props 接口进行 TypeScript 并与 defaultProps 合并
- javascript - Node.js 使用模块中的变量
- c++ - 无法在 Visual Studio 2017 中使用 QT
- javascript - 未处理的拒绝(TypeError):无法读取未定义的属性“id”
- tensorflow - 使用 tensorflow 逐步训练数据集
- java - Java中PresignedURL的SignatureDoesNotMatch