Webpack uses loaders to package static resources

Since WebPack can only package JS files, webPack doesn’t know what you want to do when you introduce Css styles into a file and an error occurs.

The installation

// Command line input
npm install css-loader style-loader
Copy the code

Open the webpack.config.js file

module: {rules:[
		{
			test:/\.css$/.use: ['style-loader'.'css-loader']]}}Copy the code

CSS – the role of the loader

// CSS-loader will help us analyze the relationship between several CSS files, and finally help us merge into one CSSCopy the code

Style – the role of the loader

// After getting the content generated by CSS-loader, style-loader will mount the content to the <head> section of the pageCopy the code

How do I package SCSS files

With additional loader (Sass-loader)

NPM install sass-loader node-sass –sava-dev

Open the webpack.config.js file

module: {rules:[
		{
			test:/\.css$/.use: ['style-loader'.'css-loader'.'sass-loader']]}}Copy the code

(Note: loader is loaded from bottom to top and from right to left. The order in use cannot be changed.)

You need to add the compatibility prefix when encountering compatibility problems

1. Install

npm install -D postcss-loader

npm install autoprefixer -D

2. Open the webpack.config.js file

module: {rules:[
		{
			test:/\.css$/.use: ['style-loader'.'css-loader'.'sass-loader'.'postcss-loader']]}}Copy the code

3. Create the postcss.config.js file in the root directory

module.exports = {
	plugins: [require('autoprefixer')]}Copy the code

Common configuration items in CSS-Loader

1. Open the webpack.config.js file

module: {rules:[
		{
			test:/\.scss$/.use: ['style-loader'.// Change the original 'CSS-loader' to an object
				{
					loader:'css-loader'.options: {// Webpack may not execute 'sass-loader' and 'postCSs-loader' when importing other SCSS. If importLoader:2 is added, webpack will execute again in that order
						importLoaders:2.// CSS modularity: only applies to the current module and does not affect other modules
						modules:true}},'sass-loader'.'postcss-loader']]}}Copy the code

(Note: CSS modularity is introduced in files when import style from ‘./index.scss’)

How to package third-party font files

Icon official website: www.iconfont.cn/

The installation

Run the NPM install file-loader -d command

1. Open the webpack.config.js file

module:{ rules:[ { test:/\.css$/, use:['style-loader','css-loader','sass-loader','postcss-loader'] }, {/ / packaging external third-party font test: / \. (eot | the vera.ttf | SVSG) /, use: {/ / is actually from the SRC directory down under the dist file loader: 'file - loader'}}}]Copy the code

Read more about Webpack at webpack.js.org/loaders/