CodeBlanks Logo Icon CodeBlanks

Shared packages

Learn shared packages and code sharing.

Shared packages

The power of a monorepo comes from shared packages. packages/ui ships components to every app, packages/utils helper functions, packages/theme a theme. Each package has its own package.json.

Package names are usually scoped: @my/ui, @my/utils. This avoids collisions and makes grouping easy on npm. Apps add these packages as dependencies.

Importing from a package

A shared package is added as a dependency to the app's package.json. Then it is used with a normal import: import { Button } from '@my/ui';. Yarn/npm sets up a symlink; changes apply instantly.

The package's main or exports field tells which file to import. For unpublished packages, "@my/ui": "*" uses the local copy.

Practice Use the Button package

Inside an App component, import Button from the @my/ui package. Render a Button with the title prop set to "Save".

Starter code

App.js
import React from 'react';

// Import Button from @my/ui

export default function App() {
  return null;
}

Sample solution

App.js
import React from 'react';
import { Button } from '@my/ui';

export default function App() {
  return <Button title="Save" />;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the scoped package name

Question
A common name for a shared UI package is ____.
Answer
A common name for a shared UI package is @my/ui.

Explanation: @my/ui is a scoped package name.

2 Match the package names

Term Meaning
@my/ui Components
@my/utils Helpers
@my/theme Theme
@my/api API client

3 How is a shared package imported?

  • With a normal import
  • With fetch
  • With AsyncStorage Correct answer
  • With Platform.OS

Explanation: A shared package is used with a normal import.

All lessons in Expert