Building an Angular Library
Angular libraries are built for supporting many different services and functionality. Angular libraries can be built using Vite that can be published to npm.
Creating a Library
If you are creating a new package, use the library
schematic:
ng generate lib my-lib
For an existing library, follow the setup instructions.
Setup
Install the @analogjs/platform
package:
- npm
- Yarn
- pnpm
npm install @analogjs/platform --save-dev
yarn add @analogjs/platform --dev
pnpm install -w @analogjs/platform
Next, create a vite.config.ts
at the root of the project, and configure it to build the library.
Update the references to
my-lib
to match the library project name.
import { defineConfig } from 'vite';
import angular from '@analogjs/vite-plugin-angular';
export default defineConfig(({ mode }) => ({
root: __dirname,
cacheDir: '../../node_modules/.vite/libs/my-lib',
plugins: [angular()],
resolve: {
mainFields: ['module'],
},
build: {
target: ['esnext'],
sourcemap: true,
lib: {
// Library entry point
entry: 'src/public-api.ts',
// Package output path, must contain fesm2022
fileName: `fesm2022/my-lib`,
// Publish as ESM package
formats: ['es'],
},
rollupOptions: {
// Add external libraries that should be excluded from the bundle
external: [/^@angular\/.*/, 'rxjs', 'rxjs/operators'],
output: {
// Produce a single file bundle
preserveModules: false,
},
},
minify: false,
},
}));
Next, update the project configuration to use the @analogjs/platform:vite
builder to build the library.
{
"name": "my-lib",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "projects/my-lib/src",
"prefix": "lib",
"projectType": "library",
"architect": {
"build": {
"builder": "@analogjs/platform:vite",
"options": {
"configFile": "projects/my-lib/vite.config.ts",
"outputPath": "dist/projects/my-lib"
},
"defaultConfiguration": "production",
"configurations": {
"development": {
"mode": "development"
},
"production": {
"sourcemap": true,
"mode": "production"
}
}
}
}
}