快速开始

安装 css-loader style-loader

1
npm install css-loader style-loader --save-dev

在 src 文件夹下新增style.css文件

1
2
3
4
/* style.css */
p {
color: red;
}

此时目录结构

1
2
3
4
5
6
7
8
9
10
11
12
webpack
|- /dist
|-index.bundle.js
|-index.html
|- /node_modules;
|- /src
|- index.html
|- index.js
|- style.css
|- package-lock.json
|- package.json;
|- webpack.config.js

index.js中引入 css 文件

1
2
3
// index.js
import './style.css';
console.log('hello webpack');

编辑 webpakc.config.js

1
2
3
4
5
6
7
8
9
// add
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},

img
此时执行 npm run build
控制台提示报错
The ‘mode’ option has not been set, webpack will fallback to ‘production’ for this value.
Set ‘mode’ option to ‘development’ or ‘production’ to enable defaults for each environment.

编辑 webpakc.config.js

1
2
// add
mode: "development",

img

再次执行 npm run build 在浏览器查看dist 目录下的index.html可以看到颜色已经变成红色了.