7

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

Masaru Nagaya
  • 71
  • 1
  • 2

1 Answers1

7

You should use node-fetch@2.6.1 because node-fetch only support ESM recent versions.

related: Instead change the require of index.js, to a dynamic import() which is available in all CommonJS modules

sizumita
  • 71
  • 1
  • 3