Skip to content

Share code between apps

An Astro app can import from any library of the workspace. This guide shares an Astro component; TypeScript modules work the same way.

A directory with a project.json is enough:

libs/ui/project.json
{
"name": "ui",
"sourceRoot": "libs/ui/src"
}
libs/ui/src/Button.astro
---
interface Props {
href: string;
}
const { href } = Astro.props;
---
<a class="button" href={href}><slot /></a>

Give it an alias for the whole workspace:

tsconfig.base.json
{
"compilerOptions": {
"paths": {
"@acme/ui/*": ["./libs/ui/src/*"]
}
}
}

The paths of a tsconfig.json replace inherited ones. The application and import generators therefore copy the aliases of the workspace into each new app. An app that existed before the library needs the alias by hand:

apps/my-app/tsconfig.json
{
"extends": "./tsconfig.base.json",
"include": [".astro/types.d.ts", "**/*", "../../libs/ui/src/**/*"],
"exclude": ["dist"],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@acme/ui/*": ["../../libs/ui/src/*"]
}
}
}

The include entry is needed only when the workspace config sets composite, as the ts preset of Nx does. Without it nx check reports error 6307 in such a workspace.

apps/my-app/src/pages/index.astro
---
import Button from '@acme/ui/Button.astro';
---
<Button href="/contact">Contact us</Button>
Terminal window
nx build my-app

Imports in .astro files are part of the project graph. my-app now depends on ui, so:

  • the targets build of libraries run before the one of the app,
  • a change in libs/ui makes the cached build of my-app outdated,
  • nx affected -t build builds my-app after such a change.

See it with:

Terminal window
nx graph
  • Imports in .mdx files are not followed.
  • <script src="…"> is not followed. An import inside a <script> is.
  • Aliases of libraries that are created later are not added to existing apps.
  • Nx keeps the dependencies of files that did not change. After editing aliases, run nx reset.

For the first two, name the library in implicitDependencies of the app’s project.json.

nx-astro 3.2.0 · MIT Developed by