One of my favourite additions to Aurelia 2 is proper support for Shadow DOM and with it, the ability to encapsulate my styles on a per-component basis, it works well most of the time. However, if you’re using a CSS library such as Bootstrap or legacy CSS, you will need to add in some global CSS styling.
Fortunately, Aurelia makes it easy to add in shared CSS styles. In-fact, if you use npx makes aurelia
to create a new Aurelia 2 application and choose Shadow DOM, it automatically adds some code into main.ts
which allows you to add shared CSS styles.
For those of you using Bootstrap or some generic CSS reset such as Normalize, you’re going to encounter a problem where CSS styles targeting classes will work, but anything that targets generic HTML tags like body will not be “shared” across your app, they will be ignored.
I encountered this issue while attempting to use Bootstrap 5 in an Aurelia 2 application. The solution I came up with might not be the best solution, but it’s an acceptable one.
Inside of your index.ejs
file you want to add the Bootstrap 5 CSS file from the CDN they provide:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
Secondly, you want to make sure that Bootstrap 5 is installed (or relevant CSS library) and import the CSS from within your main.ts
file.
import shared from './shared-styles.css'; import bootstrapStyles from 'bootstrap/dist/css/bootstrap.css'; Aurelia.register( StyleConfiguration.shadowDOM({ sharedStyles: [bootstrapStyles, shared], }) ) .app(MyApp) .start();
Because of the limitations of Shadow Dom and shared styles, I had to include it in my index.ejs
file for the styling for HTML elements and then shared for the classes. It might seem a bit redundant, but it worked for my needs. I am sure there must be a way to handle all of this with Webpack, right now, I am just too lazy to find out.
I wrote this article because I know others are going to encounter the same issues and it just saves time and hassle.