Steps for incorporating universal style into Angular 6/7 library

I attempted to incorporate global styles in my Angular app similar to how it's done, but unfortunately, it didn't work as expected.

The library I'm using is named example-lib. To include the styles, I added styles.css in the directory /projects/example-lib/. In the main angular.json file, I included the styles like this:

...
"example-lib": {
  "root": "projects/example-lib",
  "sourceRoot": "projects/example-lib/src",
  "projectType": "library",
  "prefix": "ngx",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
        "tsConfig": "projects/example-lib/tsconfig.lib.json",
        "project": "projects/example-lib/ng-package.json",
        "styles": [
          "projects/example-lib/styles.css" <!-- HERE 
        ],
      },
...

When attempting to build the library with the command:

ng build example-lib

An error occurred:

  Schema validation failed with the following errors:
  Data path "" should NOT have additional properties(styles)

I believe there might be another method for adding global styles to a separate library. Can anyone provide guidance on this?

Answer №1

If you're looking for a way to make the styles of your library component global, I have a solution for you. By setting the view encapsulation to none in the root component, all styles will become global.

my-library.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'lib-my-library',
  templateUrl: './my-library.component.html',
  styleUrls: ['./my-library.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class MyLibraryComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

my-library.component.html

<!-- html content -->

my-library.component.scss

@import './styles/core.scss';

Your my-library.component.scss and core.scss files are now global.

styles/core.scss

body {
    background: #333;
}

You can also include mixins and variables by following this answer.

Answer №2

As previously mentioned by @codeepic, there is an existing standard solution.

To implement this in your project, simply add the following lines to your ng-package.json:

"assets": ["./styles/**/*.css"]

Make sure to adjust the paths to match your file locations, as they will also be mirrored in your /dist folder after building.

Once the build process is complete, users of your library can easily include these stylesheets in their projects using the following syntax:

/* styles.css */
@import url('node_modules/<your-library-name>/styles/<file-name>');

This method allows you to copy various types of files for distribution.

Additionally, keep in mind that when working with CSS, you have the option to create an index.css file which can be imported in a similar manner as

node_modules/<your-library-name>/styles
.

Answer №3

Based on the article Compiling css in new Angular 6 libraries:

  1. To bundle the css, we need to install some devDependencies in our library:

    • ng-packagr
    • scss-bundle
    • ts-node
  2. Create a file called css-bundle.ts and add the following code:

    import { relative } from 'path';
    import { Bundler } from 'scss-bundle';
    import { writeFile } from 'fs-extra';
    
    /** Bundles all SCSS files into a single file */
    async function bundleScss() {
      const { found, bundledContent, imports } = await new Bundler()
        .Bundle('./src/_theme.scss', ['./src/**/*.scss']);
    
      if (imports) {
        const cwd = process.cwd();
    
        const filesNotFound = imports
          .filter(x => !x.found)
          .map(x => relative(cwd, x.filePath));
    
        if (filesNotFound.length) {
          console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
          throw new Error('One or more SCSS imports failed');
        }
      }
    
      if (found) {
        await writeFile('./dist/_theme.scss', bundledContent);
      }
    }
    
    bundleScss();
    
  3. Add _theme.scss inside the /src directory of the library that contains and imports all the css to be bundled.

  4. Include a postbuild npm script to run the css-bundle.ts

  5. Finally, include it in the styles tag of your Application in the angular.json file

Answer №4

Discover the solution for this particular issue

To resolve this, make sure to include cpx and scss-bundle as development dependencies in your package.json. Then, insert the following code within the "scripts" section of your package.json:

"scripts": {
  ...
  "build-mylib": "ng build mylib && npm run build-mylib-styles && npm run cp-mylib-assets",
  "build-mylib-styles": "cpx \"./projects/mylib/src/lib/style/**/*\" \"./dist/mylib/style\" && scss-bundle -e ./projects/mylib/src/lib/style/_style.scss -d ./dist/mylib/style/_styles.scss",
  "cp-mylib-assets": "cpx \"./src/assets/**/*\" \"./dist/mylib/assets\"",
  ...
}

Ensure to replace "mylib" with your actual library name before running the command build-mylib in your terminal. This will compile your scss assets into the dist folder.

If you wish to use these global styles in your current Angular project, remember to import them in your angular.json file under project settings:

"styles": [
  "src/styles.scss",
  "dist/my-shiny-library/_theme.scss"
],

(use dist if your project is in the same workspace, or node_module if it's an imported library)

Answer №5

1- Make sure to include your styles within the library directory

For example:

projects/your-lib-name/assets/styles.css

2- Next, in your ng-package.json file (located within the library), add the assets rule

    {
      "$schema": ...  , 
      "dest": ...   , 
>     "assets": [
>         "./assets/*"
>       ],
      "lib": ...
    }

3- Within your application, you can now utilize this asset

  "styles": [
              "../your-lib-name/assets/styles.css"
            ]

Check out this tutorial for more guidance

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

Checkable Ionic Table

I'm curious about achieving a similar functionality to this example using Angular and Ionic, but without relying on jQuery. Here is the link for reference: Any advice on how to accomplish this would be appreciated. Thank you. ...

TS2339: The 'map' property is not available on the 'Object' type

I'm currently working with the following code snippet: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/op ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Align list items vertically, even when they have varying heights

I am currently working on creating rows of images, with 3 images in each row. The data being used is dynamic, however, I have provided some sample HTML and CSS below: ul { margin: 0; padding: 0; list-style: none; width: 900px; } li { margin: 0; padding: ...

Designing a toggle button interface with Material UI

Looking to add a toggle button to my page. Here is an image of what I have in mind: https://i.sstatic.net/tiQAP.png Unable to find any material-ui component or API for this specific toggle button design. Considering building a custom toggle button with CS ...

Does the color of the item change as it gets older?

How can I smoothly transition a color as it ages using a dynamic time scale? I want to calculate the age based on the difference in time rather than triggering an animation after an event. I aim for a seamless gradient transition between two colors over a ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

MVC Template with a Defective BootStrap

Struggling with creating an MVC master template along with sub-pages using Bootstrap. Sadly, I seem to have messed it up and can't quite figure out where the problem lies. You can check out my test website at Do you see how the different sections a ...

Developing interconnected dropdowns in Angular 8 for input fields

Imagine we have a list of names structured like this: nameSelected: string; names: Name[ {firstName: 'John', middleName: 'Danny', lastName: 'Smith'}, {firstName: 'Bob', middleName: 'Chris', lastN ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

What is the best way to navigate between different areas of an image using html and javascript?

I am currently in the process of learning how to develop mobile applications, and I am still in the early stages. Although this question is not directly related to mobile development, it pertains more to html/css/js. My goal is to create a simple game wh ...

Using the feColorMatrix SVG filter in CSS versus applying it in JavaScript yields varied outcomes

If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet: ctx.filter = "url(#b ...

What's the best way to make sure my table fits perfectly within its container's width?

I've encountered an issue with a table: If you want to see how the table was created, check it out on jsFiddle I attempted to modify the CSS like this : table{ width:100%; } td span { float:right; width:20%; text-align:center ...

The primary container is brimming with an abundance of content

Can anyone help me with a CSS issue I'm experiencing in the latest versions of Chrome and Firefox? I can't seem to figure it out on my own. The problem arises with a container div that has a 50px top margin. Inside this container, there's a ...

What is the process of playing blob videos (avi, mov) in Angular14?

I've been struggling with this issue for quite some time without knowing how to resolve it. After some research, I came across a similar question: how to play blob video in angular. However, the problem is that the demo provided in the answer does no ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

Require that double-width unicode symbols are displayed as double-width in Markdown or CSS

I am seeking a solution to manage the visual width of double-width unicode characters like the LARGE ORANGE SQUARE ...

Tips for keeping a div centered even when the window is resized to smaller than the background width

I need help with centering a background image within a content div that is inside a wrapper container. When the browser window is resized to less than 500px, the background image starts to cut off from the right side. How can I ensure the background image ...

What is the best way to incorporate infinite scrolling into my Angular carousel implementation?

After following an amazing tutorial, I was able to create a basic carousel using two directives and one component in Angular. However, the current version of the carousel lacks an 'infinite scrolling' mode, which is something I would like to inc ...