GoogleCloudPlatform / functions-framework-nodejs

FaaS (Function as a service) framework for writing portable Node.js functions
Apache License 2.0
1.29k stars 158 forks source link

Issue finding cloudEvent function in Bundled JS file #477

Closed RaminKav closed 1 year ago

RaminKav commented 1 year ago

I have a typescript project that has a couple cloudEvent functions. I want to test these functions with functions-framework.

They work in javascript using tsc, using the script FUNCTION_TARGET=test npx functions-framework --signature-type=cloudevent

However, when i try to bundle my project (which is necessary when i eventually need to deploy this to GCP, since it uses a lot of dependencies from other folders in my monorepo), i get the following error when running the above script:

$ FUNCTION_TARGET=test npx functions-framework --signature-type=cloudevent

Function 'test' is not defined in the provided module.
Did you specify the correct target function to execute?
Could not load the function, shutting down.

looking through the bundled JS file, i can find the function is there. I suspect something with the imports of functions-framework might not be working/registering the cloudEvent properly in the bundled file?

Ive tried with both esbuild and vercel/ncc

Here is a snippet of the vercel/ncc bundle:

(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true }));

const gfunction = __nccwpck_require__(249);

gfunction.cloudEvent('test', cloudEvent => {
    console.log('test')
});
AdDaviesAppex commented 1 year ago

Hey @RaminKav, did you solve this issue? I am getting something very similar when bundling with webpack.

aidinrs commented 1 year ago

@AdamDaviesAppex I got the same problem. It is caused by having two separate module instances of the @google-cloud/functions-framework module. One is bundled with your code and one is run with the CLI command.

@google-cloud/functions-framework uses a map variable to register the handler. In this case, the handler is registered with the bundled instance and the instance ran with the CLI returns undefined. One solution is to filter '@google-cloud/functions-framework' from bundling.

If you are using webpack, add these lines to your config file:

    externalsType: 'commonjs',
    externals: ['@google-cloud/functions-framework'],
pocesar commented 1 year ago

@Aidiiin you just saved me from hours trying to make this thing work, thanks