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.
Create a library
Section titled “Create a library”A directory with a project.json is enough:
{ "name": "ui", "sourceRoot": "libs/ui/src"}---interface Props { href: string;}const { href } = Astro.props;---
<a class="button" href={href}><slot /></a>Give it an alias for the whole workspace:
{ "compilerOptions": { "paths": { "@acme/ui/*": ["./libs/ui/src/*"] } }}Add the alias to existing apps
Section titled “Add the alias to existing apps”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:
{ "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.
Import it
Section titled “Import it”---import Button from '@acme/ui/Button.astro';---
<Button href="/contact">Contact us</Button>nx build my-appWhat Nx sees
Section titled “What Nx sees”Imports in .astro files are part of the project graph. my-app now depends on ui, so:
- the targets
buildof libraries run before the one of the app, - a change in
libs/uimakes the cached build ofmy-appoutdated, nx affected -t buildbuildsmy-appafter such a change.
See it with:
nx graphLimits
Section titled “Limits”- Imports in
.mdxfiles are not followed. <script src="…">is not followed. Animportinside 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.