webpack4系列教程,如何提取css文件并插入代码到html?
发布于 作者:苏南大叔 来源:程序如此灵动~
大家好,在本篇教程中,苏南大叔继续说的是:webpack@4如何在.js代码中,提取css文件,并且插入到模板之中。从效果上来说,和处理js的过程比较相似。需要安装个新的插件mini-css-extract-plugin,并进行配置。

webpack@4系列中,处理css的插件,名字叫做:mini-css-extract-plugin。注意:网络流传的相关插件叫做:extract-text-webpack-plugin,但是它已经废弃了。不能在webpack@4系列中使用。
本文测试环境:win10、node@14.2.0、npm@6.14.4、webpack@4.43.0、mini-css-extract-plugin@0.9.0、css-loader@3.5.3。
安装插件
在webpak@4中处理css的插件叫做:mini-css-extract-plugin。另外,本文的方案正确执行,还需要css-loader这个webpack插件。它们的安装命令如下:
npm i mini-css-extract-plugin css-loader -D对于网上流传的安装extract-text-webpack-plugin的说法,如果您不是最新的webpack@4系列版本的话,那么,您也可以试试extract-text-webpack-plugin。
基本使用方法
当然,还是要配置webpack.config.js这个配置文件。
const path = require("path");
var MiniCssExtractPlugin = require("mini-css-extract-plugin");
//...
module.exports = {
mode: 'production', // 环境
entry: {
//...
main: './src/main.js'
},
output: {
filename: 'js/[name].[hash:8].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
//...
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'css/[name].[hash:8].css',
// chunkFilename: '[id].css',
}),
new HtmlWebpackPlugin({
template:"./html/index.html", // 根据 目标文件生成 html
title: 'Output Management',
showErrors: true,
inject: 'body',
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
// options: {
// publicPath: '/public/path/to/',
// },
},
'css-loader',
],
}
]
},
}
这个插件,可以完美的把css插入到html模板的<head>区域,还是比较好用的。css的路径是ouput.path和new MiniCssExtractPlugin的filename的两者组合。

引入css文件
对于webpack来说,.css文件是依托.js文件而存在的。引入的方式是import。例如:main.js:
import "./test.css"
// import url from './test.css'
console.log("aa")webpack并不直接认识.css文件,它是通过loader识别css文件的。需要正确配置相关loader,否则,您可能会看到下面类似的错误信息:

ERROR in ./src/test.css 1:4
Module parse failed: Unexpected token (1:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> body{
| background: red;
| }
@ ./src/main.js 4:0-28这个主要的原因就是没有配置.css文件的loader。
相关链接
extract-text-webpack-plugin已经被废弃,无法在webpack@4系列中使用,替代者是:mini-css-extract-plugin。
更多链接:
总结
这个提取css的配置,明显复杂很多。在市面上,还有更多处理css文件的loader,但是,这里苏南大叔就说这几个实用的。
更多webpack@4系列教程,请参考苏南大叔的博客: