Search code examples
typescriptyarnpkgnetlifylernayarn-workspaces

Using UI Library as a Dependency for Web App on Netlify Monorepo (Yarn Workspace/Lerna)


I have two apps, glowystuff-web, and glowy-ui. Glowy-UI is a shared UI lib, that I plan to use on other projects, kind of my own React Bootstrap.

Here's the challenge. I have glowy-ui defined as a dependency in packages/glowystuff-web/package.json as follows:

{
 "dependencies": {
   "glowy-ui": "*"
 },
 "scripts": {
  "build": "gatsby build"
 }
}

Unless I run yarn build (which compiles using tsc to glowy-ui/lib) and commit the JS lib/ files to git (yuck!) I get errors like this build:

3:47:15 PM: failed Building production JavaScript and CSS bundles - 24.131s
3:47:15 PM: error Generating JavaScript bundles failed
3:47:15 PM: Can't resolve 'glowy-ui' in '/opt/build/repo/packages/glowystuff-web/src/components'
3:47:15 PM: If you're trying to use a package make sure that 'glowy-ui' is installed. If you're trying to use a local file make sure that the path is correct.

For context, these are the Best instructions I've found for Monorepos (with Yarn Workspaces) on Netlify:

https://community.netlify.com/t/difficulty-with-new-monorepo-deployment-options/4381/9

What's unclear to me is how I get Netlify to know that building needs to happen. If I did this on packages/glowystuff-web/package.json:

"scripts": {
  "build": "yarn workspace glowy-ui build && gatsby build"
}

... then it seems like it would build the UI lib on every build of the main web app, glowystuff-web, even when there were no updates to the UI lib code.

A private, published NPM package for glowy-ui could be a workable option here, but my idea was to have a single GitHub repo with Yarn Workspaces, where I don't need to publish. After all, why publish if all the files are available for reading?

So what's the best approach, on Netlify/Yarn Workspaces, to make things build, but also take advantage of caching when appropriate?

Additional context on current builds - netlify.tomls:

We are using the code-as-config approach to Netlify builds. Here is current packages/glowystuff-web/netlify.toml:

[build]
  publish = "public/"
  command = "yarn build"

Glowy-UI is both the UI lib, and the accompanying storybook app, so here is current packages/glowy-ui/netlify.toml:

[build]
  publish = "storybook-static"
  command = "yarn build-storybook"

Solution

  • You can go with the post install stage to build glowy-ui library. This stage will create build every time you will run yarn install.

    scripts: {
       "build": "gatsby build",
       "postinstall": "yarn workspace glowy-ui build"
    }
    

    Edit This postinstall works only when we are running after npm/yarn install. i.e. it will not run on every build. In case of Netlify it also checks for package.json update. If not it will not run yarn install which will not invalidate this package cache. No node_modules from netlify deploy