How to use node-fetch with Cloud Functions for Firebase. Can't deploy
You should use [email protected] because node-fetch only support ESM recent versions.
Masaru Nagaya
Updated on January 01, 2023Comments
-
Masaru Nagaya about 1 year
I wanna get data with Cloud Functions call from Flutter.
Here is my code.
const functions = require("firebase-functions"); const admin = require('firebase-admin'); const fetch = require('node-fetch'); admin.initializeApp(); exports.postalCode = functions.https.onCall( (data, context) => { const URL = 'https://zipcloud.ibsnet.co.jp/api/search?zipcode=100-0002'; return fetch(URL).then(res => res.json()); });
Error code
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/xxx/node_modules/node-fetch/src/index.js
require() of ES modules is not supported. require() of /Users/xxx/node_modules/node-fetch/src/index.js from /Users/xxx/xxx/functions/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /Users/xxx/node_modules/node-fetch/src/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/xxx/node_modules/node-fetch/package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13) at Module.load (internal/modules/cjs/loader.js:950:32) at Function.Module._load (internal/modules/cjs/loader.js:790:14) at Module.require (internal/modules/cjs/loader.js:974:19) at require (internal/modules/cjs/helpers.js:92:18) at Object.<anonymous> (/Users/nagayamasaru/Togashop/functions/index.js:3:15) at Module._compile (internal/modules/cjs/loader.js:1085:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10) at Module.load (internal/modules/cjs/loader.js:950:32) at Function.Module._load (internal/modules/cjs/loader.js:790:14)
package.json
{ "name": "functions", "description": "Cloud Functions for Firebase", "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "14" }, "main": "index.js", "dependencies": { "firebase-admin": "^9.8.0", "firebase-functions": "^3.14.1", "node-fetch": "file:node_modules/node-fetch" }, "devDependencies": { "eslint": "^7.6.0", "eslint-config-google": "^0.14.0", "firebase-functions-test": "^0.2.0" }, "private": true }
How to Solve??? Thanks your support from Japan
-
marco alves over 2 yearsSame issue here but with typescript
-
cpper almost 2 yearsI got the same issue
-