Yarn Workspaces — Monorepo Approach

See how Yarn Workspaces allow developers to develop mobile & web applications using monorepo approach, helps to split and share code between multiple packages.

KPITENG

Projects grow over time and some pieces of code can be useful elsewhere in other projects. Also we need to share code between projects like Redux, ApolloClient, MobX — State Management Library, Common Utilities, etc same for both React Native, React.js or other technologies.

Please download full source code from our GitHub.

Monorepos

Many projects used by JavaScript developers are managed as monorepos like, Babel, React, Jest, Vue, Angular.

What is Yarn Workspaces?

Step By Step Integration

Set Up Yarn Workspaces -

Create a file named package.json, Specify two things

Now, let’s create folder directory

Now, let’s jump into common folder

Same way let’s go to server directory

Go to common folder, Create file index.js

Here, I have an export function which prints logs.

Now, let’s go to Server folder and create file index.js and paste following code,

Now, let’s run this, but it will break because server doesn’t know common exists, to tell server we need to add dependency in server’s package.json

Now, let’s do yarn install to link directory, Go to server directory and trigger,

Now, let’s check our dependency are properly mapped, Go to root directory do,

So, our dependency property links with workspaces, not let’s try our server/index.js

If you want to change any message in common/index.js then it will automatically reflect using symlink

Let’s change common/index.js

And trigger,

Update Package Name — @sharecode

Go To — common/package.json

Go To — common/package.json

Go To — server/index.js

Now, let’s do yarn install to update package

Managing Folder Structure / Hierarchy -

And move common and server packages inside it.

We also need to change our package.json from main folder

So, package will be changed, so let’s rm node_modules and install again

It will install dependency again with update packages directory

Now, you can try,

Now, If you want to install any dependency for your server packages

It will install dependency in root node_modules and it will be added as dependency in server/package.json, It means node_module installed common / root node_modules. Let’s cross check it, Go to root directory

It means there is one graphql package that will work for whole workspaces which is very nice in workspaces concept.

Please download full source code from our GitHub.

What Next?

Leran, Lerna Workspaces — Managing Projects With Multiple Packages

Thanks for reading full article!

Read More Technical Articles

KPITENG || hello@kpiteng.com ||DIGITAL TRANSFORMATION

Connect Us — Linkedin | Facebook | Instagram