webpack之ExtractTextPlugin插件

为什么要使用ExtractTextPlugin?不用行不行?

如果不用的话,会产生一些css和js混乱的问题,让我们一起将在不用ExtractTextPlugin的情景重现一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = {
entry: {
'index': ['./src/index.js']
},
ouput: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
]
}
]
}
}

然后查看打包结果index.bundle.js,可以发现,css被打包到了js文件中,以字符串的形式存在,并且整个index.bundle.js比平常大了不少。就像这样:

1
exports.push([module.i, "p{\n, color: red;\n}", ""]);

此时如果有html引用该JS

1
2
3
4
5
6
7
8
9
<html>
<head>
<title></title>
<script src="./../dist/index.bundle.js"></script>
</head>
<body>
<p>text</p>
</body>
</html>

浏览器打开index.html,就会发现cssstyle的形式被插到了head

如果使用ExtractTextPlugin插件,修改一下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module.exports = {
entry: {
'index': ['./src/index.js']
},
ouput: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
// use: [
// { loader: "style-loader" },
// { loader: "css-loader" },
// ]
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader",
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}

打包并查看dist,可以发现,index.bundle.js文件恢复了正常,并多出来一个styles.css文件。如果配合HtmlWebpackPlugin插件则自动插入index.html中。

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title></title>
<link rel="stylesheet" href="styles.css">
<script src="./../dist/index.bundle.js"></script>
</head>
<body>
<p>text</p>
</body>
</html>

ExtractTextPlugin插件属性

  • new ExtractTextPlugin(options:filename|object) :

    • id:此为插件的唯一标识,默认为自动生成。
    • filename:定义文件的名称。如果有多个入口文件时,应该定义为:[name].css。
    • allChunks:当使用 CommonsChunkPlugin 并且在公共 chunk 中有提取的 chunk(来自ExtractTextPlugin.extract)时,allChunks **必须设置为 true
    • ignoreOrder:禁用顺序检查 (这对 CSS 模块很有用!),默认 false
    • disable:禁用插件
  • ExtractTextPlugin.extract(options:loader|object) :

    • options.use:指需要什么样的loader去编译文件
    • options.fallback:编译后用什么loader来提取css文件
    • options.publicfile:用来覆盖项目路径,生成该css文件的文件路径
-------------要说再见啦感谢大佬的光临~-------------