Repository: portal
Kalmar Energi frontend Monorepo
Section titled “Kalmar Energi frontend Monorepo”This repository contains frontend applications for Kalmar Energi.
It uses NX to handle the monorepo setup.
Read more in the getting started documentation
Or the NX blog
Or follow the NX youtube channel
Pipeline naming convention (Azure DevOps)
Section titled “Pipeline naming convention (Azure DevOps)”Use this format for pipeline definition files:
<lifecycle>-<scope>-<action>-<environment>.yml
lifecycle:ci,cd,opsscope: what is targeted (for exampleaffected,dependabot)action: what the pipeline does (for examplevalidate,deploy,update)environment: include when relevant (for exampledev,prod)
Current pipeline files:
ci-affected-validate.ymlcd-affected-deploy-dev.ymlops-dependabot-update.yml
When renaming pipeline files, update the pipeline YAML path in Azure DevOps pipeline settings to match the new filename.
VS Code Extensions
Section titled “VS Code Extensions”It’s recommended to install the following VS Code extensions to enhance your development experience:
- NX Console: This official NX plugin provides generators and commands to make it easier to work with NX.
- Angular Language Service: This plugin helps with code completion while writing Angular code.
- ESLint: Provides feedback for when ESLint rules are not followed.
- Prettier: A code formatter that helps maintain consistent code style.
- Tailwind CSS IntelliSense: Provides intelligent autocompletion, linting, and hover support for Tailwind CSS.
Development
Section titled “Development”Use the correct node version
Section titled “Use the correct node version”If you’re using nvm, run nvm use to install the version defined in the .nvmrc file of this repository. If not, manually switch to the node version stated in the file.
Install dependencies
Section titled “Install dependencies”To install development dependencies run:
npm installLocal development server
Section titled “Local development server”To start development servers for all angular applications in parallel, run:
npm startTo start a development server for any given angular application run:
npx nx serve [app-name]For example:
npx nx serve portalor
npx nx run portal:serve:developmentTo start development servers for multiple, specific applications in parallel, run:
npx nx run-many -t [target] -p [project],[project]For example:
npx nx run-many -t serve -p customer-formula,portalOther commands
Section titled “Other commands”You can read about running NX tasks in the Run tasks NX documentation.
To run build command against a given app run:
npx nx run portal:build:productionTo run lint command against a given app run:
npx nx run portal:lintor
npx nx run portal:lint --fixGenerate libs/components
Section titled “Generate libs/components”You can read about the generate command in the Generate NX documentation.
If the NX Console extension is installed in your code editor, you can right click a folder in the workspace and select the “NX Genereate” option in the action menu to get an interactive UI which can generate a command.
Use the --dryRun flag to see what will be generated without actually running the command.
To generate a new library run:
npx nx g @nx/angular:library [lib-name] --tags=[tag-name]For example:
npx nx g @nx/angular:library dashboard --tags=dashboardTo generate component inside the library, run:
npx nx g @nx/angular:component my-component --project=dashboard --standaloneTo generate a standalone component inside the features library
npx nx g @nx/angular:component not-found --project=features --standalone --exportThis component can later be imported like:
import { NotFoundComponent } from "@kalmarenergi/features";or
loadComponent: () => import("@kalmarenergi/features").then((m) => m.NotFoundComponent),Interactive Dependency graph
Section titled “Interactive Dependency graph”To view interactive project graph, run:
npm run graphRun target for affected projects
Section titled “Run target for affected projects”You can read about the affected command in the Affected NX Documentation.
To inspect what’s been affected by changes in the project graph (compared with the main branch), run:
npm run nx affected:graph --base=master --head=HEADRun tests for current changes:
npm run nx affected:testrun e2e tests for current changes
npm run nx affected:e2eGenerate locale/translations
Section titled “Generate locale/translations”You can read about the extract-i18n executor in the @nx/angular:extract-i18n NX Documentation.
To run i18n command for the portal project, run:
npm run portal:extract-localeClear cache
Section titled “Clear cache”Clears the local NX cache and shuts down the NX daemon.
npx nx resetGuidelines
Section titled “Guidelines”Angular style guide
Section titled “Angular style guide”This project follows the Angular style guide. It is recommended to follow the guidelines in the style guide when writing code.
Import aliases
Section titled “Import aliases”Import aliases are set up in the tsconfig.base.json file. To import a module, use the alias defined in the paths object. Generating a new library or application with NX will automatically add an alias to the tsconfig.base.json file.
Code formatting
Section titled “Code formatting”This project uses EditorConfig, Prettier, and ESLint to enforce code formatting and style. Make sure to have the recommended extensions installed in your code editor to gain auto format on save functionality and be notified about potential lint errors.
.editorconfig file is used to define the coding styles for different editors and IDEs.
.prettierrc file is used to define the code formatting rules. It does not currently include any rules, but can be added if needed.
eslint.config.mjs files define the linting rules: the root file holds the shared rules, and each project’s own file extends it.
Module boundaries
Section titled “Module boundaries”The repository is divided into libraries and applications. Libraries are shared across applications and contain reusable code. Applications are standalone projects that use libraries to build the application.
In general, the following guidelines should be followed:
- Libraries should not depend on applications.
- Applications should not depend on other applications.
- Applications should only depend on libraries.
In the root eslint.config.mjs file, the @nx/enforce-module-boundaries rule is used to enforce module boundaries. In the depConstraints array, you can define the module boundaries that should be enforced.
Testing
Section titled “Testing”Component tests are written with the help of Angular Testing Library
This will reduce the amount of implementation details in the component tests and make them more maintainable, compared with using the Angular TestBed.
Testing other parts of the application, like services and utilities, should be done solely with Jest if possible.
A video tutorial on how to write Angular unit tests, focusing on Angular services: Angular Unit Testing Course - All That You Need to Know About Testing
Pipes, directives, and other Angular-specific tests should be written with the Angular TestBed.
Principles and practices
Section titled “Principles and practices”Why do we test? Testing is important because it helps us to:
- Ensure that the code works as expected.
- Prevent bugs and regressions.
- Improve code quality.
- Make the codebase more maintainable.
- Increase confidence in the codebase.
- Facilitate collaboration and communication between team members.
- Tests can work as documentation for the codebase
What do we test? We can test different aspects of the codebase, but we should focus on testing the following:
- Business logic: Test the business logic of the application to ensure that it works as expected.
- User interface: Test the user interface to ensure that it is user-friendly, accessible and provides correct feedback.
- Integration: Test the integration between different parts of the application to ensure that they work together correctly.
- Business critical paths: Test the critical paths of the application to ensure that they work as expected.
Snapshot testing is a useful tool for testing the user interface of the application. It can help to ensure that the user interface is consistent and that it works as expected. Read about snapshot testing in the official Jest documentation.
There are pitfalls to avoid when writing snapshot tests, so it is of upmost importance to follow best practices. Read about effective snapshot testing in the blog post by Kent C. Dodds. There is also a great article on how to make great snapshot tests with jest on Medium.
“The more your tests resemble the way your software is used, the more confidence they can give you.” - @kentcdodds on X
Be sure to read and understand the following articles on testing. This will help us write fewer, more readable and maintainable tests that provide more value.
Write tests. Not too many. Mostly integration.
Good testing practices with 🦔 Angular Testing Library
Angular testing library examples on Github
Styling
Section titled “Styling”The styling in this project is set up using a combination of SCSS (global styles, Angular Material theme) and Tailwind CSS v4 (utilities).
Tailwind CSS
Section titled “Tailwind CSS”Tailwind is configured in CSS, not in tailwind.config.js. A single workspace-root .postcssrc.json runs @tailwindcss/postcss for every app and both Storybooks.
| File | Purpose |
|---|---|
libs/ui/src/styles/tailwind.css | KE flavor: prefix tw:, Material/KE colour theme (@theme inline), 3xl breakpoint, dark: variant on .tw-dark, v3 compatibility base rules. Used by portal and the ui/identity Storybooks. |
libs/calc/src/styles/tailwind.css | Calculator flavor: no prefix, calculator colours. Used by apps/calculator and libs/calc. |
apps/customer-formula/src/tailwind.css | Customer-formula flavor and entry: prefix tw:, default Tailwind palette. |
apps/<app>/src/tailwind.css, libs/<lib>/.storybook/tailwind.css | Entries: import a flavor and list the @source folders to scan. Added to the styles array in project.json. |
Rules:
- Classes use the
tw:prefix variant first:tw:flex,tw:md:p-4,tw:hover:underline,tw:-mt-2, important astw:p-0!. The old v3 syntax (tw-flex,!tw-p-0) is silently ignored by v4. In the calculator write plainflex. - Utilities live in a cascade layer, so unlayered CSS (Angular Material component styles, global SCSS) beats them regardless of specificity. To override Material on the same element, use the important modifier (
tw:text-error!). - A component stylesheet that uses
@applymust reference its flavor after any@uselines, e.g.@reference "../../styles/tailwind.css";. Never put@referenceor@import "tailwindcss"in a Sass partial that is@used by another file. Prefer plain CSS (with--theme(--shadow-sm inline)) over@applyof shadows, rings and borders in component styles: those utilities add@propertyrules that count against the component style budget. - When an app (or Storybook library) gains a new library dependency, add an
@sourceline for that library to its entry file. Otherwise classes used only in that library are not generated.npm run lint:tailwindchecks this against the Nx project graph and also rejects oldtw-syntax; it runs in CI. - In watch mode new classes are picked up on rebuild; removed classes stay in the CSS until the dev server is restarted.
SCSS (Sassy CSS) is a CSS preprocessor that adds features like variables, nesting, and mixins. It’s used in this project to define global styles and theming. The main SCSS files are:
-
libs/ui/src/styles/theme.scss: This file defines the global theme for applications and for angular material components, including colors, fonts, and other design elements. -
libs/ui/src/styles/typography.scss: This file defines the global typography styles for the project.
These SCSS files are imported into the styles.scss file in each application, which is then included in the apps/<app-name>/project.json file as a global style (after the app’s tailwind.css entry).
Typography
Section titled “Typography”The typography can be set up using the typography.scss file in the libs/ui/src/styles folder. This file defines the global typography styles for the application, including font families, sizes, weights, and line heights.
If using this approach, be sure to include the material symbols and roboto font files in the assets folder of the application. Check the portal application for an example of how to set up the typography.
Update related dependencies
Section titled “Update related dependencies”NX migrate
Section titled “NX migrate”Upgrades NX, angular and other dependencies that have been setup with the monorepo.
To read more about this command, read migrate NX Documentation.
There is a video tutorial that explains NX migrate on youtube.
To migrate to the latest version of NX and related dependencies, run:
npm run migrateThis will update the package.json and create a migration.json file (if necessary).
The next steps will potentially include:
- Installing new package versions with
npm install. - Running migrations with
npx nx migrate --run-migrations.
The terminal in which the migrate script was run will prompt you with which steps to take.
Maintain other dependencies
Section titled “Maintain other dependencies”To upgrade all dependencies to latest minor version run:
npx npm-check-updates --upgrade --target "minor"To update all angular related dependencies to latest available minor/patch version run:
npx npm-check-updates --upgrade --target "minor" --filter "/@angular.*/"⚠ It’s recommended to handle updates of angular related packages with the
nx migratecommand described above.
To update all typescript/eslint related dependencies to latest available minor/patch version run:
npx npm-check-updates --upgrade --target "minor" --filter "@typescript-eslint/*"Developer tooling
Section titled “Developer tooling”Storybook
Section titled “Storybook”Some libs and applications in this monorepo are using Storybook. From the documentation:
Storybook is a frontend workshop for building UI components and pages in isolation. It helps you develop and share hard-to-reach states and edge cases without needing to run your whole app. Thousands of teams use it for UI development, testing, and documentation. It’s open source and free.
Running storybook
Section titled “Running storybook”Run storybook: npx nx run <project-name>:storybook
This will open up a browser showing available stories for that project.
Setting up storybook in a new project
Section titled “Setting up storybook in a new project”To generate storybook for a new lib or application: npx nx g @nx/angular:storybook-configuration <project-name>. A new folder named .storybook will be generated containing main.ts and preview.ts.
Optional step: A file named preview-head.html can be added in the storybook folder with the following contents to preload fonts and icons:
<!doctype html><html> <head> <link rel="preload" href="assets/fonts/roboto-v30-latin-regular.woff2" crossorigin="anonymous" as="font" type="font/woff2" /> <link rel="preload" href="assets/fonts/material-symbols-outlined.woff2" crossorigin="anonymous" as="font" type="font/woff2" /> </head></html>Static assets should be placed in the <project_path>/.storybook/assets folder. In the example above, the fonts are placed in the <project_path>/.storybook/assets/fonts folder.
For storybook to make the static assets available, add the following to <project_path>/.storybook/main.ts:
import type { StorybookConfig } from "@storybook/angular";
const config: StorybookConfig = { stories: ["../**/*.@(mdx|stories.@(js|jsx|ts|tsx))"], addons: ["@chromatic-com/storybook", "@storybook/addon-docs"], framework: { name: "@storybook/angular", options: {}, }, staticDirs: [{ from: "./assets", to: "/assets" }], // Add this line docs: {},};
export default config;Storybook 10 removed the
@storybook/addon-essentialsand@storybook/addon-interactionspackages; docs, controls and actions now ship in the core plus@storybook/addon-docs. The webpack builder is selected by@storybook/angularitself, so nocore.builderentry is needed.
Storybook needs the localize polyfill to be able to process any component or dependencies including localizations. Add the following line to the top of the <project_path>/.storybook/preview.ts file:
import "@angular/localize/init";In your project.json, located in the root of the project, add the styles attribute under options to your generated storybook configuration:
"storybook": { "executor": "@storybook/angular:start-storybook", "options": { "port": 4400, "configDir": "libs/ui/.storybook", "browserTarget": "ui:build-storybook", "compodoc": false, "styles": ["apps/portal/src/styles.scss"] // Add this line }, "configurations": { "ci": { "quiet": true } } },Creating a story
Section titled “Creating a story”- Go to a component folder where you would like to add a story
- Create a
.component.stories.ts file
File structure for stories:
state|- components |- <component-name> |- <component-name>.component.stories.ts |- <component-name>.component.ts |- <component-name>.component.html |- <component-name>.component.scss |- <component-name>.component.spec.tsTo write your stories, have a look at the Storybook documentation
Sort dependencies
Section titled “Sort dependencies”Sort all dependencies and scripts in the package.json file by running:
npx sort-package-jsonVendors
Section titled “Vendors”The following dependencies are installed from static files in the vendor folder:
xlsx
SheetJS are currently (or permanently) uploading new versions via their own CDN. See https://git.sheetjs.com/sheetjs/sheetjs/issues/2667
Because of this, the package can not be installed via npm anymore. To not depend on SheetJS CDN being online during npm installs, the static file is saved as a vendor module.
A regular check in the changelog is prefferable to determine if any new version should be downloaded to upgrade the package.