简体   繁体   中英

Firebase Cloud Functions - "not defined" error for npm dependency & including a module with client side code

I'm developing an app with Firebase and I'm using Cloud Functions to generate a QR code, among other things.

I have two problems :

1, I'm trying to use the qrcodejs npm package in Cloud Functions.
I ran sudo npm install --save qrcodejs in my functions directory.

This is the relevant part of the package.js file in the functions directory:

"dependencies": {
    "firebase-admin": "~5.8.1",
    "firebase-functions": "^0.8.1",
    "kjua": "^0.1.2",
    "qrcodejs": "^1.0.0"
  },

When the code is deployed and runs, I get a 'QRCode is not defined' error in the Cloud Functions log .

This is my functions/index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var qrcodejs = require('qrcodejs')

exports.events = functions.https.onRequest((req, res) => {

  const eventID = req.path
  const promise = admin.database()
  .ref('events' + eventID)
  .once('value')

  return promise.then(result => {

    var qrcode = new QRCode("test", {
      text: "http://jindo.dev.naver.com/collie",
      width: 128,
      height: 128,
      colorDark : "#000000",
      colorLight : "#ffffff",
      correctLevel : QRCode.CorrectLevel.H
    });

    var html = `
    <!doctype html>
      <head>
        <title>${result.val().title}</title>
      </head>
      <body>
        ${qrcode}</br>
        ${result.val().title}
      </body>
    </html>`

    return res.status(200).send(html);
  });
});

The error points to this line: var qrcode = new QRCode("test", { . I'm pretty sure I'm doing the insertion into the html string wrong as well, but the error points to the line above.

2, I've tried using another qr code npm package too, kjua . I'd much prefer to use kjua , but I'm having an additional problem with that.

Upon running firebase deploy I get the following error at the ' i functions: preparing functions directory for uploading... ' step:

ReferenceError: window is not defined

It points to the second line of the functions/node_modules/kjua/dist/kjua.min.js file.

The problem seems to be that the code is written as it were run in a browser. Can I still include this package as a dependency in Cloud Functions somehow?

Thank you very much

For sake of Answer, for people like me you just need to replace

window with global and it works in node.js / cloud functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM