Angular + Webpack - How to add global CSS styles to Angular with webpack
The below steps show how to quickly add a global LESS / CSS stylesheet to your Angular application using Webpack. To find out how to setup an Angular app with Webpack see Angular 7 Tutorial Part 2 - Create Base Project Structure & Webpack Config.
Install LESS / CSS webpack loaders into your Angular project
Run the following command from the root folder of your Angular project to install the npm packages required to convert LESS styles into CSS, then load the CSS styles and inject them into the DOM.
npm i --save-dev css-loader less less-loader style-loader
Create global LESS / CSS stylesheet for your Angular app
Create a LESS stylesheet named app.less
alongside your root Angular app component (/src/app/app.component.ts
) with some simple styles for testing, for example:
body {
background-color: #1abc9c;
}
Add module rules to your Angular webpack config
Update your webpack.config
with the following module rules so webpack knows how to process *.less
files.
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
}
This is the complete Angular webpack config file from the above example app after the style loaders have been added:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/main.ts',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
use: ['ts-loader', 'angular2-template-loader']
},
{
test: /\.(html|css)$/,
use: 'raw-loader'
},
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
}
]
},
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' })
],
devServer: {
historyApiFallback: true
}
}
Import global LESS / CSS stylesheet into Angular app component
Import the app.less
global stylesheet into your root Angular app component (/src/app/app.component.ts
) with the following line.
import './app.less';
This is the complete app.component.ts
file from the above example app after the global stylesheet has been imported:
import { Component } from '@angular/core';
import './app.less';
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {}
Need Some Angular Help?
Search fiverr for freelance Angular developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!