Include external CSS in an Angular library by modules

Viewed 639

I am working on an angular design library based on bootstrap, similar to ng-bootstrap

I currently created multiples modules for each design component that can be imported separately based on user needs.

ex :

src/
  modules/
    inputs/
    buttons/
    navs/
    tooltips/
    .... 

Each module can be imported independently and used in application.

The problem I face is with bootstrap scss. Has explained here we can import all bootstrap with

@import "../node_modules/bootstrap/scss/bootstrap";

or by chunk

@import "../node_modules/bootstrap/scss/root";
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
@import "../node_modules/bootstrap/scss/images";
@import "../node_modules/bootstrap/scss/containers";
@import "../node_modules/bootstrap/scss/grid";

I would like each of my modules to import their specific scss files. The table would import the tables scss, the navs the navs etc...

Since bootstrap files are scss they need to be compiled before added to the page, and the easy solution of manually adding in each module a stylesheet element would not work.

In ng-bootstrap they require users to manually add each bootstrap scss that they wish to use, but this could be kind of a pain for users since they need to manually add a module and the associated styles.

Are there any solution to bind a scss file to a module, and compile it if that module is used in the app ?

1 Answers

I would follow in the footsteps of Angular Material's implementation and provide users of your library instructions on how to include the design library styles default styles or custom styles. Take a look at Angular Materials build code and the corresponding exported assets made available as an NPM package. Essentially to manually import a single SCSS file per module that is imported as described above a user would need to take the following steps and understand the styles will be applied globally. There is no dynamic inclusion and compilation of SCSS in Angular upon loading of a module the chunks under the hood would need to be recompiled and the styles would be preprocessed again.

In angular.json under the "build.options" object modify "styles" and "stylePreprocessorOptions" and update the configuration to point to the new global styles directory "entry" such as "styles":["src/styles/styles.scss"], "stylePreprocessorOptions": { "includePaths": [ "styles" ] } then in styles.scss import your bootstrap scss. Under the styles directory you can now create a custom directory structure and the angular compiler will be able to find everything imported in the global "styles.scss" file. Further reading: read about the shadow DOM in Angular in the context of styles applied based on view encapsulation for component scoped styles vs. globally applied styles.

Related