13

Angular 2: how to import your css file with Webpack without errors

 3 years ago
source link: https://marco.dev/2017/02/21/angular-how-to-import-your-css-file-with-webpack-without-errors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java-version.com: What's new in Java 16? 15? Keep up to date!

Angular 2: how to import your css file with Webpack without errors

According to the Angular documentation load an external style file in a component is as easy as :

template:
    `
        <h2></h2>
        <hero-team [hero]=hero></hero-team>
        <ng-content></ng-content>
    `,
styleUrls: ['app/hero-details.component.css']

This configuration is challenging when you have building process that include Webpack. In our reference example application the call of the css file using styleUrl

@Component({
    selector: 'cv-experience',
    templateUrl:'cv-experience.html',
    styleUrls:['cv.css']
})

resulted in this error:

{'Uncaught Error: Expected 'styles' to be an array of strings. at assertArrayOfStrings (eval at <anonymous> '}

To solve the issue we had to migrate from Webpack 1.x to the new version 2 and call the css file with the following code:

    @Component({
        selector: 'cv-experience',
        templateUrl:'cv-experience.html',
        styles:[require('./cv.css').toString()]
    })

This is the loader of Webpack

    { test: /\.css$/, loader: "style-loader!css-loader" },
    { test: /\.scss$/,loaders: ['style', 'css', 'postcss', 'sass'] }

Author

Marco Molteni

Marco Molteni Blog


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK