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

I'm wondering why my second div is displaying a different size compared to the rest, even though they all share the same container-fluid class

Within the HTML snippet provided, utilizing Bootstrap, all three child divs possess the container-fluid class. However, why does the 2nd div differ from the others? Refer to this example Div Example. Div1 and div4 exhibit the same characteristics, as do d ...

Eliminating Angular's @Injectable decorator in npm build process

I have encountered a setback while working on a small helper package for Angular. The issue I am facing is related to an exported class that serves as an Angular service and is decorated with @Injectable(). After running npm run build, the compiled class ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...

The z-index property fails to function properly when used with a relative parent and after/before pseudo-elements

Here is the code snippet (prototype) that I am working with: .headerz { position: relative; padding: 5rem 0 0 5rem; margin: 3rem 0 0 0; color: #000; font-size: 3.8rem; text-transform: uppercase; z-index: 24; } .headerz::before { content ...

Creating a custom extended version of Angular2 Http does not automatically provide injection of services

I'm struggling to understand this issue. I've created a custom class that extends Angular's Http class. import { Injectable } from '@angular/core'; { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, ...

Encountered a typing issue with the rowHeight property in Angular Material

Utilizing angular and angular material, I'm creating a mat-grid-list using the following code: template <mat-grid-list cols="2" [rowHeight]="rowHeight | async"> component rowHeight = this.breakpointObserver.observe(Breakp ...

What are the steps to get started with AngularJS 2?

When starting an Angular 1.XX project, we typically use the following code to bootstrap: ng-app ="myApp" Then in our Javascript file, we set up our app like so: var app = angular.module('myApp',[]); But how do we go about bootstrapping in Ang ...

A newline within the source code that does not display as a space when rendered

Written in Chinese, I have a lengthy paragraph that lacks spaces as the language's punctuation automatically creates spacing. The issue arises when inputting this paragraph into VSCode - there's no seamless way to incorporate line breaks in the s ...

Is there a way I can add opacity to a div without impacting the other elements contained in it?

When I set the opacity of a div, it seems to affect all the other elements inside that div by making them transparent too. However, I am looking for a solution where the child elements do not inherit the opacity of their parent. Any assistance on this is ...

Ways to align one child to the end without affecting any other elements

I'm attempting to position only div3 at the flex-end of .app. If I use this code: .app { display: flex; flex-direction: column; height: 100vh; justify-content: flex-end; } Div3 goes where I want it, but everything else also moves dow ...

What distinguishes line-height:1.5 from line-height:150% in CSS?

Does anyone have any information on this? ...

What is the solution to prevent the inadvertent activation of onmouseEnter when onmouseLeave

I recently created a CSS/Jquery script that enlarges a DIV and replaces a font awesome icon with some text when hovered over, then changes it back to the icon when the mouse leaves. However, I noticed in the console that when I remove the mouse from the DI ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

The transparency feature using rgba is not supported in the Chrome browser for Android

Have you noticed the transparency effect in certain divs using the rgba CSS property? Strangely, Chrome on my ASUS tablet and Samsung S3 mini Galaxy smartphone does not seem to support this feature. Surprisingly, Internet Explorer does! Any insights on w ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Webpage expands its reach beyond the confines of the HTML element

I've recently added a background gradient to my webpage to make it easier on the eyes, but now I've noticed that the page extends past the <html> element and continues scrolling. This also causes the background gradient to repeat below the ...

What causes a slow disappearance of both the form element and its child elements when the visibility attribute is set to hidden on the

Have you ever noticed that the child elements of an element form hide slowly when using visibility:hidden, but hide quickly when using display:none? This slow hiding can negatively impact user experience. I tried to find information on this issue, but eve ...

Unable to locate element in the DOM using XPath

Having trouble retrieving an element from the DOM using XPath <input bsdatepicker="" class="form-control font-size-normal ng-untouched ng-pristine ng-valid" id="endDate" name="endDate" placement="top" type="text"> The value of the element is not p ...

Animated collapse with margin effect in Material-UI

I have been utilizing the MUI-Collapse component to display collapsible content within a list. I am looking to add vertical spacing between the Collapse components in the list, but I do not want the spacing to remain when the Collapse is collapsed. I am ha ...

Guidelines for utilizing NgFor with Observable and Async Pipe to create Child Component once the data has been loaded

Encountering an issue while attempting to display a child component using data from an Observable in its parent, and then utilizing the async pipe to transform the data into a list of objects for rendering with *NgFor. Here's what I've done: C ...