Error Encountered: Anticipated 'styles' to consist of a series of string elements

I have attempted various solutions for this particular error message without any success. When launching my angular project using the angular cli via ng serve, everything runs smoothly with no errors. However, upon compiling it with webpack, I encounter the following (detailed) error message:

Uncaught Error: Expected 'styles' to be an array of strings.
    at z (vendor.js:1)
    at t.getNonNormalizedDirectiveMetadata (vendor.js:1)
    at t.loadDirectiveMetadata (vendor.js:1)
    at vendor.js:1
    at Array.forEach (<anonymous>)
    at vendor.js:1
    at Array.forEach (<anonymous>)
    at t._loadModules (vendor.js:1)
    at t._compileModuleAndComponents (vendor.js:1)
    at t.compileModuleAsync (vendor.js:1)
    at e._bootstrapModuleWithZone (vendor.js:1)
    at e.bootstrapModule (vendor.js:1)
    at Object.<anonymous> (app.js:1)
    at Object.199 (app.js:1)
    at e (vendor.js:1)
    at window.webpackJsonp (vendor.js:1)
    at app.js:1

This is my webpack.config.js file:

// Required Plugins

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

// Configuration

module.exports = {

    entry: {
        app: "./src/main.ts",
        vendor: ["./src/vendor.ts", "./src/polyfills.ts"]
    },

    output: {
        publicPath: "",
        path: __dirname + "/dist/",
        filename: "[name].js"
    },

    resolve: {
        extensions: ['.ts', '.js']
      },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    {
                    loader: "awesome-typescript-loader",
                    options: { tsconfig: "tsconfig.json" }
                    }, "angular2-template-loader"
                ]
            },
            {
                test: /\.(html)$/,
                loaders: [
                    {
                        loader: "html-loader"
                    }
                ]
            },
            {
                test: /\.(css|scss)$/,
                loaders: ['to-string-loader', 'css-loader', 'sass-loader']
            }
        ]
    },

    plugins: [
        new webpack.optimize.UglifyJsPlugin({ 
            comments: false
        }),
        new webpack.optimize.CommonsChunkPlugin({
                names: ["app", "vendor"]
        }),
        new HtmlWebpackPlugin({
            template: "src/index.tpl.html",
            inject: "body",
            filename: "index.html"
        })
    ]

}

My .angular-cli.json file:

{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "index": "index.tpl.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts"
    }
  ],
  "defaults": {
    "styleExt": "css"
  }
}

app-root / app.component.ts

import { Component } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { NgFor } from "@angular/common";

@Component ({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})

export class AppComponent { 

}

Any insights into what might be going wrong in my setup would be greatly appreciated.

Answer №1

I successfully configured my webpack settings to accommodate both scss and css files. In this particular setup, which involved using Angular Storybook, the webpack configuration was located in ./storybook. I had a global stylesheet in app/styles that required some additional adjustments due to its importation of other stylesheets within the directory using relative paths. Additionally, there was a custom stylesheet in the same directory as the webpack file (./):

webpack.config.js

const path = require('path');
const autoprefixer = require('autoprefixer');
const postCSSCustomProperties = require('postcss-custom-properties');

const postcssPlugins = () => [
    require('postcss-flexbugs-fixes'),
    autoprefixer({ flexbox: 'no-2009' }),
    postCSSCustomProperties({ warnings: true })
];
module.exports = (baseConfig, env, config) => {
  baseConfig.module.rules = [
    ...baseConfig.module.rules.filter(r => !r.test.toString().includes(".s(c|a)ss")), // base rules supplied by Angular Storybook
    ...
    {
      test: /\.css$/,
      use: [
        'raw-loader',
        {
            loader: 'postcss-loader',
            options: {
                plugins: postcssPlugins
            }
        }
      ]
    },
    { // component scss loader
      test: /\.scss$/,
      include: [path.resolve(__dirname, '../')],
      exclude: [path.resolve(__dirname, '../app/styles'), path.resolve(__dirname, './')],
      use: [
        'raw-loader',
        {
            loader: 'postcss-loader',
            options: {
                plugins: postcssPlugins
            }
        },
        'sass-loader'
      ]
    },
    { // global and storybook scss loader
      test: /\.scss$/,
      include: [path.resolve(__dirname, '../app/styles'), path.resolve(__dirname, './')],
      loaders: [
        'style-loader',
        'css-loader',
        'resolve-url-loader', // resolves relative imports
        'sass-loader?sourceMap' // sourcemap = true to assist resolve-url-loader
      ]
    },
    ...
  ];

  baseConfig.resolve.extensions.push(".css", ".scss");
  baseConfig.resolve.alias = {
    ...baseConfig.resolve.alias,
    "assets": path.resolve(__dirname, "../app/assets") // needed to resolve relative paths in imported scss using an alias, where the imported files referred to sheets like "url(~assets/path/to/pic.jpg)"
  }

  return baseConfig;
};

package.json

"dependencies": {
   "@angular/core": "^6.1.3",
   "resolve-url-loader": "^3.0.0",
},
"devDependencies": {
   "@ngtools/webpack": "6.0.8",
   "@storybook/angular": "^4.1.4",
   "css-loader": "^0.28.11",
   "postcss-custom-properties": "^7.0.0",
   "postcss-flexbugs-fixes": "^3.3.1",
   "postcss-loader": "^2.1.5",
   "raw-loader": "^0.5.1",
   "sass-loader": "^7.0.3",
   "style-loader": "^0.23.1",
   "webpack": "4.15.0"
}

Answer №2

After taking Shobhit's advice, I was able to resolve my problem by making adjustments to my webpack.config.json file:

...
rules: [
{
   test: /\.(scss|css)$/,
   use: ["raw-loader", "sass-loader"]
},
{
   test: /\.scss$/,
   exclude: [/node_modules/, /src\/app/],
   use: ExtractTextPlugin.extract({
   fallback: "style-loader",
   use: ["css-loader", "sass-loader"]
   })
}
...

In addition, I included the following:

plugins: [
   new ExtractTextPlugin("styles.css")
...

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

Press the jQuery button to reset all input fields

I have created a table with input fields where class teachers can store their students' data for the principal to review. Each row in the table contains an update and reset button, allowing teachers to save or clear the information entered in the fiel ...

Steps for setting up an Angular project as a dependency in the package.json file of another Angular project

I currently have three separate Angular cli projects labeled as X, Y, and Z. My goal is to designate [X] as the parent project and include Y and Z as npm package dependencies within X. This means that the package.json file for [X] will list the dependencie ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Tips for modifying the border of an entire column in react-table

My goal is to adjust the style according to the screenshot below. This is what I expect: However, this is what I currently have: As you can see, the border bottom of the last column is not applied as expected. I have tried using the props provided by r ...

Fuzzy backdrop with razor-sharp edges

In the process of designing a website, I am in need of a header with a blurred background that retains sharp edges. To achieve this effect, I implemented the use of ::before in my CSS code. Current Outcome: (For full clarity, it may be necessary to view ...

The CSS outline has a soft, rounded appearance rather than a sharp

Is there a way to prevent my outline from having rounded corners as it expands during the animation? Note: The issue seems to be present on Linux and MS Edge, but works fine on Mozilla Firefox. Any solutions for MS Edge users? Check out the code on Codep ...

Struggling to vertically align elements within iron-pages

Struggling to vertically center the content within iron-pages (nested in a paper-drawer-panel). Check out the code snippet below: <paper-drawer-panel id="drawerPanel" responsive-width="1280px"> <div class="nav" drawer> <!-- Nav Conte ...

Creating tabbed content with a classless CSS design by utilizing radio buttons instead of the traditional unordered

I am attempting to transform the classless CSS and HTML provided below from a list format to using radio buttons and labels for tabbed content. My goal is to make it concise and avoid redundancy. Here is the setup of what I am aiming for: <nav> ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Ways to position a single item in the middle of a multi-column layout

I need help with aligning dynamic images in a 2-column layout. What's the best way to center a single image or collapse the columns when there's only one image? Currently, the single image is always placed in the left column. Is there a CSS-only ...

Require that the parent FormGroup is marked as invalid unless all nested FormGroups are deemed valid - Implementing a custom

Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types. My goal is to have the parentForm marked as invalid until all of the nested ...

Tips for achieving an eye-catching text and image layout on a single page of your Wordpress blog

I've been exploring ways to achieve a design concept for my blog layout. I envision having the text and thumbnail displayed side by side, each taking up 50% of the width until the image reaches its end. Once the image ends, I want the text to span the ...

Tips for extracting elements from an HTML document using Angular

I seem to be facing a small issue - I am trying to develop a form using Angular. Below is my HTML: <form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null"> <div class="form-group&quo ...

Angular HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...

Creating a dynamic and adaptive horizontal SVG line for your website

Understanding how SVGs function is still a bit unclear to me. I know that the viewBox property plays a role in scaling SVGs, and I have come across advice suggesting not to specify height and width attributes when creating responsive SVGs. While there are ...

Applying CSS classes to a custom AngularJS directive: A step-by-step guide

Need to have a CSS class called tab for the nav HTML element, which will be used as a directive: <nav tab></nav> The expected interpretation is: <nav class="tab"> <a></a> <a></a> <a></a> ...

Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. ...

Align text in the middle using CSS

I want to apply the following css styles #header { color: #333; width: 900px; float: left; padding: 10px; border: 1px solid #ccc; height: 150px; margin: 10px 0px 5px 0px; background-image: linear-gradient(to top, #CACACA 0%, #EFEFEF 100%); } With ...

Issue with Angular Material Slide Toggle Binding on Checked Status Not Functioning

It should be a simple task, but I'm struggling to make the checked binding for the slide toggle function properly. (My setup includes angular version 9.1 and material version 9.2.) Here is the HTML snippet: <mat-slide-toggle [checked]="isSlideCh ...

The "date" field seems to be malfunctioning on iOS devices exclusively

I'm having issues with a simple HTML CSS form that includes an input type="date" field which is not working on iOS devices. <fieldset class="form-group border p-3"> <div class="row mx-auto"> <legend class=" ...