I have a simple web component that I created with Angular. I am able to build it into one JavaScript and one css file and run it on another web page.
How do I embed the css file into the js file?
I'm confident that it can be done, but I cannot find any answers of how to do it.
The Angular project is setup to use css files. It is also using Angular Materials. The idea of defining all styles in the component files came to me. Not sure if that will result in the outcome I'm looking for though.
EDIT: To get to this point, I mainly followed the steps laid out in this tutorial.
I have now found a few tutorials that talk about changing the webpack.config file in the Angular project, but that file does not exist and I doubt it will auto-magically take it into account if I add it.
Since you are talking about "web components", for definition, I suppose you are using the shadow Dom, so setting the encapsulation of your angular component to shadowDom(the default is emulated). When you use Shadow Dom all css and html elements(Dom) are "incapsulated" inside the component(Shadow root) for avoiding conflicts with external elements. So your CSS code contained inside your component cannot affect from inside other elements, and cannot be affected from outside: this is a normal behaviour of web components. I think that you don't need the single CSS file, since you can compile your web component into a single js that contains everything inside.
If you want to manipulate the style of your component, you can use some @input property: for example:@input() background-color
, set the logic to change the background colour dynamically and when call the component from external, pass the input property:
<my-web-component [background-color]="red"/>
You can even define some CSS classes inside the component, and using the same mechanism, you can decide which of this classes to use, when your web component is being used outside of your angular application.
EDIT: How to setup shadow DOM in angular:
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
//just add this row on you component metadata decorator
encapsulation: ViewEncapsulation.None //default is ViewEncapsulation.Emulated
})
Regarding webpack take a look at this Angular CLI extension: https://github.com/manfredsteyer/ngx-build-plus