Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expecting it to be in the root directory instead. What would be the most effective approach to successfully deploy these cloud functions?

Directory Structure:

repo
  - app2
  - functions
    - cloudbuild.yaml
    - src
      - index.ts
      - onNewPostComment
         - index.ts
      - function2...
    - package.json
    - package-lock.json
    - tsconfig.json

Contents of my cloudbuild.yaml:

steps:
- name: 'gcr.io/cloud-builders/npm'
  args: [ 'install']
- name: 'gcr.io/cloud-builders/npm'
  args: [ 'run','build']
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  id: 'deploy-onNewPostComment'
  args:
  - gcloud
  - functions
  - deploy
  - onNewPostComment
  - --region=europe-west2
  - --source=.
  - --entry-point=onNewPostComment
  - --trigger-http
  - --runtime=nodejs16

package.json structure:

{
  "name": "functions",
  "scripts": {
    "build": "tsc",
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "npm run build && firebase deploy --only functions",
    ...,
  "engines": {
    "node": "16"
  },
  "main": "lib/index.js",
  ...
  "private": true
}

GCP cloud build output for npm install:

Already have image (with digest): gcr.io/cloud-builders/npm
npm WARN saveError ENOENT: no such file or directory, open '/workspace/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/workspace/package.json'
npm WARN workspace No description
npm WARN workspace No repository field.
npm WARN workspace No README data
npm WARN workspace No license field.

up to date in 0.293s
found 0 vulnerabilities

Error encountered during npm build:

Already have image (with digest): gcr.io/cloud-builders/npm
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /workspace/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/workspace/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     /builder/home/.npm/_logs/2022-07-27T09_05_46_164Z-debug.log

Answer №1

As noted in a recent article:

Original repository structure:

To start, we must establish the initial layout of our repo as follows:

docker/
  functions/
    Dockerfile
    start.sh
src/
  functions/
    http/
      helloWorld/
        index.ts
        index.test.ts
        package.json
  packages/
    lib/
      index.ts
      package.json
.eslintrc.json
.gitignore
docker-compose.yml
package.json
tsconfig.json

As mentioned in a relevant discussion:

When executing a Cloud Build job, it duplicates all files from the current directory. If you are within a subdirectory, the sibling or parent directories are not included and therefore not recognized by Cloud Build.

To address this, run your Cloud Build job at the level of the parent directory and specify the CloudBuild.yaml file in your command (directed to the appropriate subdirectory).

Remember to adjust your cloudbuild.yaml step definition because the root folder is now the main directory rather than the subdirectory. You can utilize the directory parameter to indicate the working directory for each step.

If you prefer not to upload the entirety of the monorepo during each component build, you can exclude specific files when manually triggering the gcloud builds submit command.

However, this exclusion cannot be done with triggers. You can exclude files, but in this case, those files must be disregarded in the build job trigger condition (for instance, excluding the readme file so that pushing it does not trigger a new build). Nevertheless, if the build is initiated by other files, these 'excluded files' will still be present in the running job.

For further insights on dependencies, reference the Documentation. Consider updating the node version and deploying your cloud function with the latest npm release.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering Problems Retrieving API Information in React.JS

Currently, I'm tackling a project involving a React web application and running into an issue while trying to display specific data retrieved from a mock API: Below is the code snippet in question: import React, { Component } from 'react'; ...

The dimensions of the cards adjust automatically when the flex direction is set to row

My cards, created in CSS and React.js, have a set height and width. However, when I change the flex direction from column to row, the cards automatically shrink in size. Why is this happening? Card's CSS and JS code CSS .card{ height: 50%; w ...

In Safari, there seems to be an issue where multiple URLs are not opening when clicked on from an anchor

Is there a way to open multiple URLs in Safari with just one click using window.open? I tried it, but only one URL opens in a new tab while the others do not. The version of Safari I am using is 11.0.1. onclick="window.open('URL1','_blank& ...

JS client-side form validation involves communicating with the server to verify user input

I currently have an HTML form that is being validated on the client side. Below is a snippet of the code: <form id='myForm' onsubmit='return myFormValidation()'> ... </form> Now, I want to incorporate server-side valida ...

Encountering a frustrating Npm error while trying to install a package, which persists in throwing

Encountering an error message while trying to run npm install npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\ node_modules\&bsol ...

Express.js POST Request Not Being Accepted | 404 Error Detected

I am encountering difficulties implementing PayPal on my website. Whenever I attempt a post request, including using Postman, I receive a standard 404 error page instead of the expected response. The console shows no errors, leading me to believe that the ...

What is the best way to save and reload a canvas for future use?

My current setup involves using PDF.js to display PDF documents in a web browser. The PDF.js library utilizes canvas for rendering the PDF. I have implemented JavaScript scripts that allow users to draw lines on the canvas by double-clicking, with the opti ...

The flattening of dependencies in npm 3 may not always be implemented consistently

I have encountered a situation where I have 3 dependencies, all of which reference esprima-fb. Surprisingly, they all resolve to version 15001.1001.0-dev-harmony-fb. What puzzles me is that instead of finding esprima-fb at the top level of the node_module ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

Modify the name of the document

I have a piece of code that retrieves a file from the clipboard and I need to change its name if it is named image.png. Below is the code snippet where I attempt to achieve this: @HostListener('paste', ['$event']) onPaste(e: ClipboardE ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Implementing push notifications as a standalone feature in React Native

As I work on developing a React Native application, my goal is to create an npm package for FCM Notifications. This would allow me to easily incorporate the functionality into any project by simply providing the necessary information to the package, such a ...

Creating an interactive HTML form that updates in real-time based on user input can be achieved using vanilla JavaScript. This allows for a

I am working on a form that dynamically generates more form fields based on a user input value. <form> <input type="Number" name="delivery"> </form> For example, if the user enters '3', it should automat ...

The functionality of Javascript on a website is not functioning properly when accessed through a selenium script

Why isn't Javascript functioning when I access the site through a web driver script? Here is the link to the site: . The code snippet is as follows: WebDriver d=new FirefoxDriver(); d.get("http://www.formget.com/tutorial/register_demo/registr ...

Having trouble locating async function after installation

Today, I encountered a strange issue after installing async globally in Node.js - it reported that the module could not be found. Here is the workflow: Install async npm install -g async Verify async installation npm list -g async Output received: / ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

Is there a way to disable text selection in AngularJS when double-clicking using ng-dblclick?

My element has ng-dblclick='doSomthing()' functionality that is functioning correctly, however, it also selects the text in the element which is not visually appealing. Is there a way to avoid this issue? ...

Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I susp ...

Initiating a node request utilizing the value of the array index as the req parameter

I created a method to insert a series of documents into a mongoose collection, with each entry containing the value corresponding to the next index in a range specified by upper and lower bounds. The current implementation works seamlessly when the lower ...