OiO.lk Blog CSS How can I get Angular to let me import CSS files in TypeScript?
CSS

How can I get Angular to let me import CSS files in TypeScript?


TL;DR:

I need the Angular compiler to let me import CSS files in Typescript and turn them into <style> tags in the head.

Background:

I’m migrating an existing React app over to Angular. Each React component will eventually be rewritten, but in the meantime I’m hosting them in Angular components based on this method: https://medium.com/@joseph5/rendering-react-component-in-angular-apps-9154fa3198d1.

Each React component imports its own CSS programmatically in the .tsx:

import "./MyComponent.css";

This works fine when they’re running in the original React app, but Angular doesn’t like it. Instead of rendering a <style> tag in the head like the React app does, Angular just ignores the import with no effect that I can see.

The obvious solution is to import it into the Angular host component’s .scss:

@import 'react/MyComponent/MyComponent';

The problem here is that these React components have children, grandchildren, etc, and each imports its own stylesheet. I have to dig through all of them and make sure each is imported by the Angular component. It’s a huge pain to dig through everything recursively and maybe miss one. It would be extremely helpful if I could get Angular to process the existing import statements from the .tsx the same way React does, by adding a style tag in the head. Is there any way I can do this?



You need to sign in to view this answers

Exit mobile version